1

Say I have an button with an id:

<input id='someButton' />

I want to attach an event listener on this button:

$('#form').on('click', '#someButton', function() { 
   alert("My listener called"); 

});

However, unbeknownst to me, someone previously wrote an event listener for this very same button:

$('#form').on('click', '#someButton', function() { 
   alert("Some other listener called"); 
});

I encountered some code that effectively does the same thing as above, and it seems like the first listener registered is the one that is used. Am I correct in assuming jQuery will always call the first event listener registered on a specific id (and only that listener)?

1
  • 1
    nope. in jquery you can add multiple event listeners.. Commented Mar 12, 2013 at 18:41

2 Answers 2

7

Incorrect. jQuery will call ALL event listeners bound to an element, in the order they were bound.

To remove an existing event handler, use .off():

$('#form').off('click'); // click event handler(s) removed
$('#form').off(); // all event handler(s) removed

Be aware that events delegated from ancestor DOM elements won't be removed this way, though.

Sign up to request clarification or add additional context in comments.

2 Comments

For completeness, if one of the handlers invokes stopImmediatePropagation() on the event, the handlers further down the chain will not be called. It might be the cause of the behavior observed by the questioner.
Thanks, it turns out both handlers were actually being called. Just an oversight on my part. No call was made to stopImmediatePropagation(), but that is useful knowledge to have!
0

you could use mousedown:

$('#form').on('mousedown', '#someButton', function() { 
    alert("My listener called"); 
});

Hope this help.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.