-1

I have two button classes, when clicked, I want something to happen.

I have:

$('.btn-comment, .btn-youtube').click(function(){

This used to work when the buttons were static. They are now created ad hoc.

I have tried this:

$('.btn-comment, .btn-youtube').on('click', function(){

But no luck.

panthro
  • 19,109
  • 50
  • 152
  • 271

3 Answers3

1

That's not how it works. You should add the delegation to the parent element. The one who is going to suffer from modification.

You can do it with the whole document:

$(document).on('click', '.btn-comment, .btn-youtube', function(){ ... });

But it would be better to do it with the modified element.

Alvaro
  • 37,936
  • 23
  • 138
  • 304
1

You need to register the handler on a common static ancestor (worst case document, but the nearer the better) and then use the new .on syntax for delegated handlers, e.g.:

$(document).on('click', '.btn-comment, .btn-youtube', function() { 
     ...
});
Alnitak
  • 313,276
  • 69
  • 379
  • 466
  • So if they are in a list it would be better to do: $('#myList').on('click', '.btn-comment, .btn-youtube', function(){ – panthro Sep 23 '13 at 11:52
  • 1
    @panthro indeed, unless the list element itself is also dynamically replaced. The common ancestor must be _static_. – Alnitak Sep 23 '13 at 11:52
0

Check out the jQuery docs for .on(). You need to use:

$('body').on('click', '.btn-comment, .btn-youtube', function(){ ... });

The problem with your code is that if .btn-comment, .btn-youtube are being inserted dynamically, then they probably don't exist at the point at which you're trying to attach your event handlers. The above line of code attaches the handler to body but is only triggered by elements matching the second argument ('.btn-comment, .btn-youtube').

And ideally, you'd replace 'body' with the closest ancestor that the new elements are being inserted into.

Ben Jackson
  • 10,592
  • 6
  • 29
  • 41