Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery selectors not finding class on elements in table created by an Ajax XHR in Ruby on Rails

When 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 initializes with the page, when clicking "Teh Foobar" it alerts and doesn't follow the link. However, when using the same code in application.js, and

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

is being returned into a div by a

form_remote_tag

when clicked, "Teh Foobar" fails to alert, and functions as a link.

What is happening, and how do I get around it?

like image 544
DA. Avatar asked Jan 24 '23 01:01

DA.


2 Answers

New elements added to the document after you bind your events don't automatically get those event handlers. One way to fix this is - as John Millikin says - re-bind your events after you create new elements.

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

For instance, this jQuery code would work (your syntax may vary 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 of class foo this event will get fired unless something in between catches the event and cancels the bubbling. Actually, event will be called when almost anything is clicked - the "if" statement just filters out which events deserve the alert.

like image 113
Neall Avatar answered Feb 08 '23 23:02

Neall


Markup returned from an AJAX call isn't present when you set up the page, so it doesn't have any onclick handlers associated with it. You'll need to hook into the Rails AJAX support so that when it loads your AJAX-powered div, it also executes your event setup code again.

like image 21
John Millikin Avatar answered Feb 09 '23 01:02

John Millikin