javascriptjqueryeventsevent-capturing

Capturing an event with jquery


I got a double event to manage. The two events are both "click" and they're handled with jquery. The html is the following:

 <div class="siteMap"  style="width:23%;">
            <h5>Divisione Anticontraffazione</h5>
            <span class="menufooter">
            <span class="link1"><a href="#scheda1">Introduzione</a></span><br>
            <span class="link2"><a href="#scheda2">Filosofia</a></span><br>
            <span class="link3"><a href="#scheda3">Negozio online</a></span></span><br>
        </div>

Then i have my click events which fires inside the menufooter span and inside every single link span. The code is like this:

$(document).ready(function() {
    $('span.menufooter').click(function() { 
        //my code here
    });
    $("span.link1").click(function() {
       //my code here
    });
});

I need an event capturing action, the click on the span menufooter has to fire the event before the click on the span link1 fires. At this point, none of the two events is firing. Any hint?


Solution

  • You could prevent the click from bubbling, and then trigger the click on the parent element so whatever is in that handler executes first (unless it's async)

    $(document).ready(function () {
        $('.menufooter').click(function () {
            // fires before ....
        });
    
        $("span.link1").click(function (e) {
            e.stopPropagation();
            $('.menufooter').trigger('click');
            // .... this fires, as it's triggered above
        });
    });
    

    FIDDLE