Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Span inside Anchor with event bubbling

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ł

like image 368
dragonfly Avatar asked May 28 '09 07:05

dragonfly


1 Answers

You have to use the currentTarget of your event.

$('.addToFriends a').click(function(event){
     event.currentTarget;    
     ...
});
like image 122
Christophe Eblé Avatar answered Sep 21 '22 01:09

Christophe Eblé