Forum Moderators: open

Message Too Old, No Replies

Event bubbling - how can I stop it?

         

Fotiman

4:51 pm on Oct 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have an unordered list which contains additional nested unorder lists:


<ul id="theList">
<li id="n1"><a href="#">Item 1</a></li>
<li id="n2"><a href="#">Item 2</a>
<ul>
<li id="n3"><a href="#">Item 2, Child 1</a></li>
<li id="n4"><a href="#">Item 2, Child 2</a>
<ul>
<li id="n5"><a href="#">Item 2, Child 2, Child 1</a></li>
</ul>
</li>
</ul>
</li>
</ul>

When the page loads, I assign an onclick event to all of the LI in this
list. Clicking on the item will open an alert window with the ID value of
the list item in the alert box:


startList = function()
{
if( document.getElementById)
{
// Get the list by it's ID value
listRoot = document.getElementById("theList");
// Get all of the LI items in this list
liList = listRoot.getElementsByTagName("LI");
// For each LI, add the onclick attribute
for( i = 0; i < liList.length; i++ )
{
node = liList.item(i);
node.setAttribute('onclick','alert(this.attributes.getNamedItem("id").nodeValue);');
}
}
}
window.onload=startList;

The problem I'm having is that the onclick event is "bubbling" up. That is,
if I click on "Item 2, Child 2", I will get an alert with the id "n4",
followed by an alert with an id of "n2". I want to prevent this second
event.

Does anyone have any ideas how I can kill the event after I've processed it?
I tried adding "return false;" after the alert, but that didn't make any
difference.
Thanks.

Bernard Marx

5:20 pm on Oct 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



NB: Replace corrupted ¦¦ with standard pipe chars

Last Edit 5.27 pm

window.onload = startList;

/* Use 'normal' function definition
onload assignment can then appear anywhere */
function startlist()
{
if(! document.getElementById) return;
// Get the list by it's ID value
var listRoot = document.getElementById("theList");
// Get all of the LI items in this list
var liList = listRoot.getElementsByTagName("LI");
// For each LI, add the onclick attribute
/* IE doesn't accept event handlers via setAttribute
(It does, but differently. This works everywhere)*/
for( i = 0; i < liList.length; i++ )
liList.item(i).onclick = startlist.li_onclick;
}

/* Define function outside startlist,
else closure formed, and risk of circular references */
startlist.li_onclick = function(e)
{
alert(this.attributes.getNamedItem("id").nodeValue);
// simpler? // alert(this.id);
stopPropagation(e);
}

function stopPropagation(e)
{
e = e¦¦event;/* get IE event ( not passed ) */
e.stopPropagation? e.stopPropagation() : e.cancelBubble = true;
}

Fotiman

8:28 pm on Oct 28, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Just what I was looking for. Thanks!