Antoine
Antoine

Reputation: 569

javascript code only work once, when page is loaded

Hi I have this HTML code:

            <ul class="nav navbar-nav navbar-right">
                <li>
                    <%= link_to "Articulos", articulos_path, id: "ajax_articulos" %>
                </li>
            </ul>

and whenever someone click on #ajax_articulos I want to trigger:

$(document).ready(function(){
    $( "#ajax_articulos" ).click(function() {
      alert( "Handler for .click() called." );
    });
});

My problem is that it only works at first when the page is loaded. Once the page is loaded if I click again it will not work.

How could I make that action work again even when used without having to refresh the page ?

Upvotes: 1

Views: 71

Answers (2)

jbatista
jbatista

Reputation: 1002

Which version of Ruby On Rails are you using?

If you're using RoR 5 or above with turbolinks you need do something like this:

$(document).on('turbolinks:load', function() {
  $('.some_parent_class').on('click', '#ajax_articulos', function() { 
      //Handler...
  }
})

Upvotes: 1

Leo Van Deuren
Leo Van Deuren

Reputation: 435

You can try this event using the jquery .on():

$(function() {
  $('.some_parent_class').on('click', '#ajax_articulos', function() { 
      //Handler...
  }
})

Jquery .on() function

Upvotes: 0

Related Questions