Question

I have such a piece of html:

<li class="addToFriends"><a href="....">Something something<span>INSIDE SPAN</span>something</a></li>

To handle AJAX request when clicking on anchor I have registered handler on click event:

    $('.addToFriends a').click(function(event){
    var target = $(event.target);
    if (target.is('a')) {
              // if I click on SPAN element following fragment won't execute!


      // do ajax request
    }       
    event.preventDefault();
});

My questions are:

  • why click event is raised for span element? After all, I didn't bind click event to SPAN elements
  • apart from previous question, I thought that if I won't handle SPAN click event, browser will use event-bubbling to raise click event for anchor (if I won't call event.stopPropagation()). But I also didn't work out for me as that click event is raised only once

So now, I got round that problem I my solution is:

    $('.addToFriends a').click(function(event){
    var target = $(event.target);
    if (!target.is('a')) {
      target = target.parent('a')
    } 
            ...
});

But still, I'm curious why it works like this...

Thanks,

Paweł

Was it helpful?

Solution

You have to use the currentTarget of your event.

$('.addToFriends a').click(function(event){
     event.currentTarget;    
     ...
});

OTHER TIPS

Ok, but if I click on SPAN and call stopPropagation() method my code in that form won't work:

$('.addToFriends a').click(function(event){
    var target = $(event.target);
    if (target.is('a')) {
       // do ajax request
       event.stopPropagation();               
       event.preventDefault();
    }

});

Still, I thing I'm missing some crucial points related with event bubbling.

You can always read the specification. A nice tutorial is also available here.

StopPropagation has only meaning if you have defined click event handlers for both the SPAN and A elements. Calling the stopPropagation in the SPAN event handler will prevent the A handler from being called. This assumes the default bubble phase.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top