In the example below, return false
does not seem to prevent the default action after the link is clicked (because the page scrolls to the top) in Firefox 3.6 or
return false
works cross browser, but only for event handlers assigned the "DOM0" way, such as
document.getElementById("link").onclick = function() {
alert("Clicked!");
return false;
};
For event handlers assigned the DOM Level 2 way via addEventListener()
, you have to use preventDefault()
:
document.getElementById("link").addEventListener("click", function(evt) {
alert("Clicked!");
evt.preventDefault();
}, false);
For event listeners attached via attachEvent()
in IE, either return false
or window.event.returnValue = false
will do:
document.getElementById("link").attachEvent("onclick", function() {
alert("Clicked!");
return false;
});
I have had some cross-browser issues with the return false method.
I have had good luck just replacing the href of the like with the following:
function removeLink(elementName) {
var o = document.getElementById(elementName);
o.href = 'javascript: (function(){})();';
o.target = "_self";
}
I have found that this empty function in the href property has been the easiest.
I have added the target _self part because when I develop I occasionally have these links (that I want to be hover boxes) open in a new window/tab. They need to be pointed at the current window to truly do nothing ... lol.
Hope this helps whomever.
Brynn
You say "preventDefault()
helps" but you say it doesn't work? I'm not sure I understand. Have you tried this:
addEventListener("DOMContentLoaded", function() {
document.getElementById("link").addEventListener("click", function(e) {
alert("Clicked!");
e.preventDefault();
return false;
}, false);
alert("Click handler bound!");
}, false);