How to suppress onclick event of parent div

M

Mark Smith

I have some nested div elements like this:

<div id="1" onclick="dostuff(this);">...
<div id="2" onclick="dostuff(this);">...
</div>
</div>

However when the inner div element is clicked. The outer divs onclick
fires immediately after. Is it possible to suppress this? I've tried
appending ";return false;" to the onclick events, but that didn't
work.

I don't want to go down the road of having to maintain a convoluted
set of flags, any suggestions?

Thanks
 
M

Martin Honnen

Mark said:
I have some nested div elements like this:

<div id="1" onclick="dostuff(this);">...
<div id="2" onclick="dostuff(this);">...
</div>
</div>

However when the inner div element is clicked. The outer divs onclick
fires immediately after. Is it possible to suppress this? I've tried
appending ";return false;" to the onclick events, but that didn't
work.

Events bubble up the DOM tree.
You can stop the propagation of the event with
<div id="d2" onclick="dostuff(this);
if (typeof event.stopPropagation != 'undefined')
{
event.stopPropagation();
}
if (typeof event.cancelBubble != 'undefined'
{
event.cancelBubble = true;
}">
where the stopPropagation is W3C DOM Level 2 Events compliant and
cancelBubble is the IE way.

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event
http://msdn.microsoft.com/en-us/library/ms533545(VS.85).aspx
 
D

dhtml

Mark said:
I have some nested div elements like this:

<div id="1" onclick="dostuff(this);">...
<div id="2" onclick="dostuff(this);">...
</div>
</div>

However when the inner div element is clicked. The outer divs onclick
fires immediately after. Is it possible to suppress this? I've tried
appending ";return false;" to the onclick events, but that didn't
work.

The outer div's onclick fires because the event "bubbled".

To prevent this, you can use a conditional check:-

function handleClick(ev) {
ev = ev || window.event;
if(ev.preventDefault) {
ev.preventDefault();
} else if('cancelBubble' in ev) {
ev.cancelBubble = true;
}
}

Can be used as:-

<div onclick="handleClick(event)">hey</div>

This will prevent the event from bubbling up.

Garrett
 
D

David Mark

The outer div's onclick fires because the event "bubbled".

To prevent this, you can use a conditional check:-

function handleClick(ev) {
   ev = ev || window.event;
   if(ev.preventDefault) {
     ev.preventDefault();

I'm sure you meant stopPropagation.
   } else if('cancelBubble' in ev) {

Why the variation in detection techniques? I don't really care for
either of them, though the latter is safer.

[snip]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,123
Messages
2,570,740
Members
47,295
Latest member
riya007

Latest Threads

Top