Is there is a way to only let the inner element of a listitem
do something?
I have list elements that can contain a
tags with a certain cla
The live
method in jQuery works via event delegation, which is the act of catching all the bubbled events from individual elements onto a common ancestor (in your case its document
).
Stopping the propagation/bubbling of the click event occurs on the handler element (which is the common ancestor, not on the element itself) and exists way above the li
that you are trying to avoid.
So by the time the stopPropagation
method gets called, we've already traversed down the dom and passed the li
element.
It's essentially putting a stop sign 200ft after the intersection.
So you'll either need to use bind
and stopPropagation
or find a different solution.
Here is an example of what I'm talking about: http://jsbin.com/ibuxo (check the console)
you can see the code or edit it at http://jsbin.com/ibuxo/edit
My suggested solution to this problem would be to use bind
instead of live
.
This requires you to do a little bit extra work, but it's not so bad.
You are probably using live
because you are adding new elements, and you want them to have the same functionality. You should do this by binding them when you input them to the page. Here's an example
$(function(){
var myAnchorHandler = function(e){
alert('clicked!');
e.stopPropagation();
return false;
};
// initial bind
$('#somelist li a').click(myAnchorHandler);
// code where you input more li elements to the list with links
$('#somelist').append(
// bind your function to the element now, and then append it
$('<li><a>hi</a></li>').find('a').click(myAnchorHandler).parent()
);
});
Solution from Author:
I added all the a tags like above, so no mixup with live anymore.
$(markers).each(function(i,marker){
listitem = $("<li />")
.html("Location ")
.click(function(e){
showLocation(marker, i);
})
.appendTo("#somelist");
$("<a />")
.html("<strong>"+ids[i]+"</strong>")
.addClass('ol id')
.click(function(){
$('#ginfo').show();
return false;
})
.appendTo(listitem);
Here is an interesting page to explain event bubbling: How to stop event bubbling with jquery live?
Have the handler for the <a>
tags return false.