Thursday, May 28, 2009

[jQuery] Span inside Anchor with event bubbling

Hi,

I have such a piece of html:

<li class="addToFriends"><a href="....">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();
event.stopPropagation();
});

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ł

No comments: