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 Chrome 10 but works in Internet Explorer.
Using event.preventDefault()
does what I need, but I'm wondering why return false
does not work with the others.
Side note: I do not need to support Internet Explorer.
<script>
addEventListener("DOMContentLoaded", function(){
document.getElementById("link").addEventListener("click", function(){
alert("Clicked!");
return false;
}, false);
alert("Click handler bound!");
}, false);
</script>
<div style="margin-top: 1200px;">
<a id="link" href="#">Click me!</a>
</div>
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With