views:

109

answers:

3

Hey. I've got a dumb, but nasty problem.

If I've got this (simplified) situation:

<div onclick="doSomething(); return false;">
    lorem ipsum <a href="somewhere.html">dolor sit</a> amet
</div>

...is there any (convenient) way to prevent the onclick-handler of the parent div from being triggered when the link is clicked.

In my scenario, I've got a big wrapping div that is made into a "link" with an onclick-handler, but I'd like to overlay some text data with links in it, but at least in Firefox when I click on the links in the text, the onclick of the parent is executed first.

A: 

IMHO, this is a bad nesting of HTML/behavior. Either the whole div is clickable as 1 element, or the link is, but not both... unless you "un-nest" them.

scunliffe
I think the OP recognizes this (cf "dumb...problem").
harpo
+3  A: 

With jQuery you can add a click handler to each of your anchors and use event.stopPropagation() to keep the event from bubbling up to the DIV.

   $('div#wrapperDiv > a').click( function(event) {
       event.stopPropagation();
   });
tvanfosson
event bubbling is the problem - http://www.brainjar.com/dhtml/events/default2.asp
Russ Cam
+1  A: 

You get around this by testing the original target of the event in your handler. Something along the lines of:

function doSomething ( e ) {
  // get event object and target element
  var e = e || window.event;
  var target = e.srcElement || e.target;
  // is target a div?
  if ( target && /^div$/i.test( target.nodeName ) ) {

    // do your magic in here ...

  }
}
Borgar