javascripteventsevent-handlingdom-eventsonmouseclick

Set order of mouse click events JavaScript


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.


Solution

  • 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/