I'm encountering a strange issue in my rails application, where a template fails to execute the Javascript code the first time it is loaded via a link on my home page. This problem only occurs when accessed through the link for the first time. I'm puzzled as to why this is happening. Can anyone provide assistance? Here is the relevant code snippet:
Snippet from Home Page:
#app/views/static_pages/home.html.erb
#...
<%= link_to "Notify an absence", new_cancellation_path %>
Javascript File:
//app/assets/javascripts/cancellations_new.js
var validateDateTime = function(){
// logic that returns true or false
}
$(document).ready(function(){
$("#new_cancellation").submit(function(event){
event.preventDefault();
if (validateDateTime()) {
alert("Alert message");
}
else {
// additional logic
}
});
});
Template where the Javascript should run:
#app/views/cancellations/new.erb
<%= provide(:title, "Notify an absence")%>
<div class="row">
<div class="span3 offset4">
<h3> Notify an absence </h3>
<%= form_for @cancellation, :id => "new_cancellation" do |f| %>
<%= render 'shared/error_messages' %>
<% # some form elements...%>
<%= f.submit "Send", class: "btn btn-primary"%>
<% end %>
</div>
</div>
Attempted solution by adding //= require cancellations_new
to
app/assets/javascripts/application.js
did not resolve the issue.
UPDATE
Further investigation revealed that Turbolinks could be causing the unexpected behavior of the Javascript. When Turbolinks are enabled, <a>
elements are fetched via Ajax and used to modify the <body>
of the HTML document. Due to this unconventional loading method, content within
$(document).ready(){...}
might not execute unless the page is fully reloaded. In order for your Javascript to work properly, consider changing
$(document).ready(){...}
to
$(document).on("page:change", function() {
// other logic.
});
For more information on this topic, check out these resources: here
more