views:

218

answers:

3

I have a page which has a rectangular area with text and icons in it and the whole thing is clickable. The anchor tag is set to display: block. One of the icons has an onclick handler. If a person clicks on an icon, I just want the icon's onclick handler to run and not to actually activate the containing anchor tag.

Firefox behaves like I want, IE doesn't.

So I tried to trap the event in the onclick handler:

function my_onclick_handler(evt){
  if (!evt) evt = window.event;

  // ... handle the click

  if (evt.stopPropagation) evt.stopPropagation();
  evt.cancelBubble = true;
}

That didn't work so then I thought maybe it's actually the onmouseup or onmousedown events that trigger the anchor tag so I added a clickSwallow method to onmouseup and onmousedown methods:

function clickSwallow(evt){
  if (!evt) evt = window.event;
  if (evt.stopPropagation) evt.stopPropagation();
  evt.cancelBubble = true;
}

That didn't work either. Any ideas how to keep the enclosing anchor from reacting to the click in this case?

A: 

Try to change your anchor to:

<a href="javascript:void(0)"> <img src="..." onclick=".."> </a>
idrosid
But I want the anchor to work if a person clicks within the rectangular area covered by the anchor - as long as it's not on the one image.
dl__
+1  A: 

This post has a few items yours doesn't (like e.returnValue and e.preventDefault) but from the text it appears those are FF specific functions. Might be worth a shot though.

Tom Ritter
thanks. I'll check it out.
dl__
+3  A: 

I would just use a <span>, but I think returning false from the event handler should also do the trick.

Triptych
Returning false worked. Thanks! But what did you mean about the span. Put a span around the img and add the onclick to that?
dl__
I meant use a span element instead of an anchor element, if you don't want users to follow the href anyway.
Triptych
Oh, but I do want the href to work generally. This one icon is just to display more information about what the meaning of this rectangular area is so the user would better understand why they might want to click on it.
dl__