Jagajit Prusty
Jagajit Prusty

Reputation: 2110

What will be order of execution if I am attaching two same event on a DOM

If I am attaching two click events on an element then what will be order of execution of the two handler. I know the order of execution for jQuery is the same as the order in which the events were attached. But I am not sure about the behaviour with JavaScript.

If it just appends the events handler then if I want to override all existing events handler how can I do it?

Upvotes: 2

Views: 82

Answers (2)

vassiliskrikonis
vassiliskrikonis

Reputation: 596

If all you want is to remove or override the event handlers attached by jQuery with .on() method then you could use the .off() method respectively to remove them. Then add again the handler you do want to use. Check the documentation here.

Let's say the handlers you know they are already attached are named functions like so:

function someHandler(e) {
  // do something with the event e
}

$('#myElement').on('click', someHandler);

You can remove this one by calling

$('#myElement').off('click', someHandler);

If the handlers though we anonymous functions like so:

$('#myElement').on('click', function(e) { ... } );

then you must remove all listeners attached with jQuery (jQuery keeps track of the events/listeners/handlers attached)

$('#myElement').off('click'); // remove ALL handlers for the event

Upvotes: 0

qiAlex
qiAlex

Reputation: 4346

The handlers will execute in the order in which they were bound.

The DOM3 event spec, introduces the requirement that they be fired in order of registration (what most browsers do):

Next, the implementation must determine the current target's candidate event listeners. This must be the list of all event listeners that have been registered on the current target in their order of registration.

From developer.mozilla.org

Events in the target phase will trigger all listeners on an element in the order they were registered, regardless of the useCapture parameter.-

In addition: Javascript event order

Upvotes: 2

Related Questions