0

I was reading this post

and had a question that I didn't think it answered. Why does this work:

$('#threeButtons').live('click', '.markAsSpam', function() {
     // do some stuff
});

but this doesn't:

$('#threeButtons').on('click', '.markAsSpam', function() {
     // do some stuff
});

I see the parameters are different, but I am following the example of how to use .on. At least as it applies to my example.

My DOM looks like

<div id="threeButtons">
     <a href="#" class="markAsSpam">Spam</a>
     ...
</div>

I need to use .live or .on because I am dealing with HTML that appended in the DOM. Also, my .live example only works the first time. What do I need to make it work on successive tries, without refreshing the page. I'm using jQuery 1.7 and want to use .on, since .live has been deprecated.

Community
  • 1
  • 1
sehummel
  • 5,476
  • 24
  • 90
  • 137
  • 1
    You're misusing the second argument to `.live()`. It's meant to set data on the event object. jQuery's `live()`, `delegate()` and `on()` methods use *event delegation*. It would be worth learning about it before using them. *(The `.on()` method only uses event delegation when passing providing a second argument like you did in the second example.)* –  Mar 26 '12 at 22:13
  • ...`.live()` is implicit event delegation with the handler on the `document`. This was an unfortunate decision... hence the deprecation. –  Mar 26 '12 at 22:18

1 Answers1

1

From the docs:

.live( events, data, handler(eventObject) )

So the following code will simply register a live click event for #threeButtons which will receive an additional argument .markAsSpam:

$('#threeButtons').live('click', '.markAsSpam', function() {
     // do some stuff
});

When using .on() however, you create a delegate where the click handler is bound on #threeButtons but the event will only fire if the clicked element matches the .markAsSpam selector.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Gotcha. But why does it work only once. The spam button is on every item. These are added in a for loop and then appended. – sehummel Mar 26 '12 at 22:18
  • Is `#threeButtons` added/recreated dynamically? If yes you need to use a different selector. Use `$(document).on(...)` if you want to replicate the behaviour of `.live()` – ThiefMaster Mar 26 '12 at 22:20
  • Interesting to note that as of JQuery 1.7 live, bind, delegate all now just call the .on() method. – codaniel Mar 26 '12 at 22:28