Javascript – Why can’t I trap a mouse click in IE

internet explorerjavascript

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?

Best Answer

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