caarlos0
caarlos0

Reputation: 20633

Multiple functions in the same Element and Event

What exactly happens if I add several functions in one element to the same event?

By example:

jQuery('#searchButton').click(function(){ /* logic 1 */ );
jQuery('#searchButton').click(function(){ /* logic 2 */ );
  1. always the first function added to an event will be the first to be called?
  2. all browsers support this type of thing?
  3. functions are called asynchronously?

thanks

Upvotes: 3

Views: 438

Answers (3)

davin
davin

Reputation: 45525

Just to point out something that other answers haven't yet: jQuery indeed guarantees that the events will be triggered in the order they were added (as is referenced in John Hartsock's answer) by way of binding only one event handler to any given element, and holding an internal array of functions bound (which has the additional advantage of being able to remove anonymous functions, that otherwise you wouldn't have a reference to). That then holds true for all browsers.

However, if you mix this with any other library or use the DOM directly, there are no guarantees. The standard doesn't require implementations to follow any order, so although many implement a FIFO structure internally that isn't guaranteed. Relevant section of the standard.

Upvotes: 6

swatkins
swatkins

Reputation: 13630

They're executed in the order in which they were bound. Here's an excerpt from a jquery quickstart book:

http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3

Upvotes: 1

John Hartsock
John Hartsock

Reputation: 86872

Always the first function bound to an elements event will be the first to be called?

Quote from jQuery Docs

If there are multiple handlers registered, they will always execute in the order in which they were bound.

Reference

http://api.jquery.com/bind/

Upvotes: 1

Related Questions