Peeyush
Peeyush

Reputation: 6474

jQuery Event handlers not working properly

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>

Upvotes: 0

Views: 303

Answers (1)

Sahil Grover
Sahil Grover

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

Related Questions