Reputation: 6474
The jQuery Event handlers work well on a fresh page but after I change page using the links present in layout, they stop working. I am unable to figure out what's wrong with my code.
I have the following files in my rails app:
<!DOCTYPE html>
<html>
<head>
<title>LogManager</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<h1>Analytics</h1>
<%= link_to "All",analytics_all_path %> | <%= link_to "Aggregation",analytics_aggregation_path %>
</body>
</html>
$(function() {
$("#js-analyze-aggregation").click(function(){
alert("Hehe");
});
});
$(function() {
$("#js-analyze").click(function(){
alert("Hehe");
$.ajax({
type: "GET",
url: "/api/logs",
success: function(data) {
Analytics.doAnalysis(data);
}
});
});
});
<button type="button" id="js-analyze">Analyse</button>
<textarea id="body_data" cols="60" rows="10"></textarea>
<br>
<button type="button" id="js-analyze-aggregation">Analyse Filtered Data</button>
Upvotes: 0
Views: 303
Reputation: 1915
Try changing ur JS to
$(function() {
$("#js-analyze-aggregation").on('click', function(){
alert("Hehe");
});
});
$(function() {
$("#js-analyze").on('click', function(){
alert("Hehe");
$.ajax({
type: "GET",
url: "/api/logs",
success: function(data) {
Analytics.doAnalysis(data);
}
});
});
});
When you use turbolinks, new elements come inside DOM
and event handler is not bind to them. Check here In jQuery, how to attach events to dynamic html elements?
Upvotes: 1