0

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:

layouts/application.html.erb

<!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>

analytics.js

$(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);
      }
    });
  });
});

analytics/all.html.erb

<button type="button" id="js-analyze">Analyse</button>

analytics/aggregation.html.erb

<textarea id="body_data" cols="60" rows="10"></textarea>
<br>
<button type="button" id="js-analyze-aggregation">Analyse Filtered Data</button>
Kriem
  • 8,666
  • 16
  • 72
  • 120
Peeyush
  • 6,144
  • 5
  • 23
  • 37
  • 1
    It may be related to turbolinks. Check this page: http://stackoverflow.com/questions/18770517/rails-4-how-to-use-document-ready-with-turbo-links – Baldrick Jun 06 '14 at 12:57
  • It was indeed related to turbolinks. Thanks very much for pointing out in the right direction! – Peeyush Jun 06 '14 at 13:40

1 Answers1

1

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?

Community
  • 1
  • 1
Sahil Grover
  • 1,862
  • 4
  • 26
  • 57