Search code examples
javascriptdom-events

e.preventDefault() and e.cancelBubble not working with attached listeners


I'm attempting to disable links clicked. I have an onmousedown event listener attached as such.

if(document.addEventListener){
    document.addEventListener("onmouseover", onMouseOverIdent, false);
    document.addEventListener("onmousedown", onMouseDownIdent, false);
    document.addEventListener("onmouseout", onMouseOutIdent, false);
}else{
    if(document.attachEvent){
        document.attachEvent("onmousedown",onMouseDownIdent);
        document.attachEvent("onmouseover",onMouseOverIdent);
        document.attachEvent("onmouseout", onMouseOutIdent);
    }
}

In my onmousedown function I tried using this function from quirksmode:

if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation();

However it will still do click through to the link and load it. I have not idea what could be causing it and any help would be appreciated.

UPDATE: One other thing I forgot to mention is I'm doing this on all anchor tag elements on the page. This seems to be making it more problematic to remove those listeners afterwards.


Solution

  • To make it so the href isn't followed, you should be using preventDefault instead of stopPropagation.

    For IE, you'd use

    e.returnValue = false;
    

    So it should look like this...

    if (!e) var e = window.event;
    e.returnValue = false;
    if (e.preventDefault) e.preventDefault();
    

    This assumes that the handler is directly on the link, which can't be known right now since you've excluded relevant code.


    One more thing, you're only working with the onmousedown event. If you want to prevent the behavior or disable the bubbling of the actual click event, you should be doing...

    document.addEventListener("click", ...
    document.attachEvent("onclick", ...
    

    Also, notice that addEventListener should not have "on" as part of the event name.