5

I have two elements - a parent and a child. Both have on click event handlers. If I click on the child element then both event handlers run - parent's first then child's (at least on Chrome). I don't know how the browser determines which order to run the events in, but is there a way to specifically set this order so that the child's click event happens before the parent's click event?

I have found a lot of questions and answers regarding the order of different events (mousedown, click, etc.), but can't find anything regarding the order of the same event on different elements.

1
  • By default, the child's click event should happen first. Commented Jul 8, 2015 at 22:59

1 Answer 1

5

Are you sure the parent's runs first? Events bubble from the innermost element to the outermost element (your child click handler should trigger before your parent). From http://api.jquery.com/on/:

The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element. In Internet Explorer 8 and lower, a few events such as change and submit do not natively bubble

That said, if you always want the behavior of the parent element to execute first you could do the following:

function runFirst(){
    alert("I should always run first");   
}

function runSecond(){
    alert("I should always run second");
}

$('body').on('click', '.parent', function(){

    runFirst();

}).on('click', '.child', function(event){

    runFirst();
    runSecond();

    event.stopPropagation();
});

Here's a fiddle demonstrating the behavior: https://jsfiddle.net/8fxout3d/1/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.