Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning false from click handler doesn't work in Firefox

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>
like image 256
Evgeny A. Avatar asked Mar 24 '11 17:03

Evgeny A.


1 Answers

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;
});
like image 71
Tim Down Avatar answered Sep 28 '22 21:09

Tim Down