user1017882
user1017882

Reputation:

How can I ensure a particular click event handler executes after all other attached click handlers?

I have an element:

<div id='myButton'>Click Me!</div>

When clicking on myButton, an arbitrary amount of click event handlers will fire.

For example, the following 3 event handlers may be attached in the following way (and order):

$('#myButton').click(function() { alert('First function!'); });

$('#myButton').click(function() { alert('Third function!'); });

$('#myButton').click(function() { alert('Second function!'); });

As you can maybe tell by the obscure alerts, the order in which the event handlers are attached are not necessarily the order I want them to fire in.

How can I alert 'Third Function' only once the other two click event handlers have finished?

What I've Tried

I've tried working with the individual event handlers via:

$._data($('#myButton')[0], "events" ).click;

But I can't afford to explicitly refer to the order in which the handlers are attached (so [0] might not be correct).

I've also tried using jQuery when but I suspect I'm barking up the wrong tree as the event handler is already attached and will execute in such an order unless I completely remove it.

NOTE: I don't believe this is simply a case of specifying the order of events as such, as the function I want to execute last may not be aware of the functions to be attached later on, so I can't deal with the event handlers as a collection as far as I know.

Upvotes: 1

Views: 181

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

You could use following snippet if you are able to set specific namespace:

$('#myButton').click(function() { alert('First function!'); });
$('#myButton').on("click.last", function() { alert('Third function!'); });
$('#myButton').click(function() { alert('Second function!'); });

var clicks = $._data($('#myButton')[0], "events" ).click;    

$.each(clicks, function(i, evt){
    if(evt.namespace === "last") {
        clicks.splice(clicks.length - 1, 0, clicks.splice(i, 1)[0])
    }
});

--DEMO--

Upvotes: 1

Related Questions