BaronVonKaneHoffen
BaronVonKaneHoffen

Reputation: 1990

jQuery .on() not working with jquery-ujs

So I have a rails app that renders views via jquery-ujs. (data-remote in the URLs, then a load of js.erb files with things like:

$('#whatever').html('<%= j render("form") %>');

In my main JS file, I have event handlers like so:

$('.action').on('click', function() {
    console.log("clicked");
});

but the on() behaviour does not attach to the new elements inserted by jquery-ujs. I can go into the console and paste the above code and everything attaches fine (once the elements are already there), but straight after ujs fires, no luck. Is this a bug or am I doing something wrong?

This is with jQuery 1.9.1 and Rails 3.2.13 btw.

Upvotes: 2

Views: 195

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196187

Since #whatever seems to be static (exists all the time) you can delegate the handling to it..

$('#whatever').on('click','.action', function(e){
    console.log("clicked");
});

(assuming that the .action elements are added inside the #whatever element)


See http://api.jquery.com/on/#direct-and-delegated-events for more on delegated events

Upvotes: 1

Knelis
Knelis

Reputation: 7149

You need to bind on to a parent like document. Now, you're binding directly to the .action element, which is essentially the same as using $('.action').click(). Because you're adding elements to the DOM later, you need to delegate the handler to something that's already present before the elements are inserted. You can provide a selector as the second parameter of the .on event to bind it to .action.

Have a look at the 'Direct and delegated events' section in jQuery's API documentation for .on.

This should work:

$(document).on('click', '.action', function () {
    console.log('Clicked!');
});

Upvotes: 4

Related Questions