jQuery event handlers always execute in order they were bound - any way around this?

Posted by asgeo1 on Stack Overflow See other posts from Stack Overflow or by asgeo1
Published on 2010-03-02T03:06:54Z Indexed on 2010/04/14 20:03 UTC
Read the original article Hit count: 443

Filed under:

It can be anoying that jQuery event handlers always execute in the order they were bound. For example:

$('span').click(doStuff1());
$('span').click(doStuff2());

clicking on the span will cause doStuff1() to fire, followed by doStuff2().

At the time I bind doStuff2(), I would like the option to bind it before doStuff1(), but there doesn't appear to be any easy way to do this.

I suppose most people would say, just write the code like this:

$('span').click(function (){
    doStuff2();
    doStuff1();
});

But this is just a simple example - in practise it is not always convienient to do that.

There are situations when you want to bind an event, and the object you are binding to already has events. And in this case you may simply want the new event to fire before any other existing events.

So what is the best way to achieve this in jQuery?

© Stack Overflow or respective owner

Related posts about jQuery