JQuery selectors do not find class on items in table created by Ajax XHR in Ruby on Rails

Using

$('.foo').click(function(){ alert("I haz class alertz!"); return false; }); 

in application.js and

 <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> 

in any div that is initialized on the page, when you click "Teh Foobar" it warns and does not follow the link. However, when using the same code in application.js and

 <a href = "" class = "foo" id = "foobar_1" >Teh Foobar </a> 

returns to the div on

 form_remote_tag 

when you click "Teh Foobar" a warning does not appear and works as a link.

What happens and how do I get around it?

+4
source share
3 answers

New elements added to the document after binding your events do not automatically receive these event handlers. One way to fix this - as John Millikin says - is to recreate events after creating new elements.

Another standard way is event delegation. Since events go all the way up and down the stack through all their parent elements, you can bind the event to an element that will be the ancestor of all your target elements.

For example, this jQuery code will work (your syntax may differ for other JavaScript libraries):

 $(document).ready(function() { $('body').click(function(event) { if ($(event.target).is('.foo')) { // <- this is the magic alert('Something of class foo was clicked.'); return false; } }); }); 

Now, when you click something from the foo class, this event will be fired unless something between them catches the event and cancels the bubble. In fact, an event will be raised when almost anything is pressed - the if statement simply filters out which events deserve a warning.

+3
source

The mark returned by an AJAX call is missing when setting up the page, so it does not have any onclick handlers associated with it. You need to connect to Rails AJAX support so that when you load your AJAX-active module, it will also execute your event setup code again.

+3
source

You can also use the jQuery Live Query plugin, which can automatically bind events for matched elements after updating the DOM. In your case, it will be:

 $('.foo').livequery('click', function() { alert("I haz class alertz!"); return false; }); 
+3
source

Source: https://habr.com/ru/post/1277551/


All Articles