tags:

views:

1301

answers:

1

Will execute in order 'first, second'. I need last as first executed.

function first(){ alert('first') }
function second(){ alert('second') }
$('input').click(first).click(second);
+1  A: 

Short answer: You can't do this.

Although in praxis browsers run events in the sequence that they were assigned you cannot trust that they will always do this. Also note that cancellations depend on which event model you use. In Level 1 (onclick="...") cancelling the event bubble takes effect immediately and no further handlers are run. This is not true for Level 2 (Element.addEventListener), which jQuery uses, where all handers registered on an element will always fire before propagation is stopped.

In my opinion, if you are writing something that depends on more than one handler function to run sequentially but don't have control of the sequence of assignments then you need to reconsider your approach.

However - if you must do this - you can unbind and reassign all events on the elements you need in order to get the desired sequence. You can get a list of events on a given element with $.data( someelement, 'events' ) and then un-/reassign them with your prefered event pushed to the front.

Borgar