Capturing an event with jquery

102 views Asked by At

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?

4

There are 4 answers

0
adeneo On BEST ANSWER

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

0
andyf On

How about only fire event on .menufooter

$(document).ready(function() {
    $('span.menufooter').click(function(e) { 
        //my code here 1

        // Capture Event Propagation
        if ( $("span .link1").find(e.target).length>0 ){
           //my code here 2
        };
    });
});

http://jsfiddle.net/9QLtG/

0
David On

Try this event.stopPropagation();

 $("span.link1").click(function(event) {
     event.stopPropagation();
       ...
 });
0
Charlie Schliesser On

I would have 1 click listener that listens to the wrapper. You can check the event's target to see if they actually clicked on a link and run code accordingly.

For example:

$(document).ready(function() {

    $('.container').click(function(e) {

        // Perform action when they clicked in the main wrapper,
        // regardless of whether or not it was a link.
        console.log("I clicked in the wrapper...");

        if ($(e.target).hasClass('link')) {
           // Perform action if they clicked on a link.   
           console.log("...but more specifically, on a link.");
        }
    });

});

Here's a fiddle that demonstrates this: http://jsfiddle.net/WaYFr/