views:

59

answers:

2

javascript jquery event handling if on event (for example 'click') binded one function for parent element and another handler function for child DOM element, which of them are called? If all of them will be call in which order? Thank you!

+2  A: 

Events bubble "up" the DOM tree, so if you've got handlers for an element and its parent, the child element handler will be called first.

If you register more than one handler for an event on a single DOM element (like, more than one "click" handler for a single button), then the handlers are called in the order that they were attached to the element.

Your handlers can do a few things to change what happens after they're done:

  • With the passed-in event parameter, call event.preventDefault() to keep any "native" action from happening
  • call event.stopPropagation() to keep the event from bubbling up the DOM tree
  • return false from the handler, to both stop propagation and prevent default

Note that for some input elements (checkboxes, radio buttons), the handling is a little weird. When your handler is called, the browser will have already set the checkbox "checked" value to the opposite of its former value. That is, if you have a checkbox that is not checked, then a "click" handler will notice that the "checked" attribute will be set to "true" when it is called (after the user clicks). However, if the handler returns false, the checkbox value will actually NOT be changed by the click, and it will remain un-checked. So it's like the browser does half of the "native" action (toggling the element "checked" attribute) before calling the handler, but then only really updates the element if the handler does not return false (or call "preventDefault()" on the event object).

Pointy
will be called the parent handler or no?
Andrew
The parent handler is called unless the child handler prevents that from happening - see my (edited) answer
Pointy
Thank you! this is very helpful for me.
Andrew
excellent answer.
dalbaeb
A: 

The child will be called first, then the parent.

Events go from the child to the parent as the event bubbles up. On the same element, the handlers will execute in the order they were bound.

Nick Craver