Derse geri dön
Bu materyal sadece English, Español, Français, Indonesia, Italiano, 日本語, 한국어, Русский, Українська, 简体中文 dillerinde mevcuttur. Lütfen Türkçe diline çevirmek için bize yardım edin.

Why "return false" doesn't work?

önem: 3

Why in the code below return false doesn’t work at all?

<script>
  function handler() {
    alert( "..." );
    return false;
  }
</script>

<a href="http://w3.org" onclick="handler()">the browser will go to w3.org</a>

The browser follows the URL on click, but we don’t want it.

How to fix?

When the browser reads the on* attribute like onclick, it creates the handler from its content.

For onclick="handler()" the function will be:

function(event) {
  handler() // the content of onclick
}

Now we can see that the value returned by handler() is not used and does not affect the result.

The fix is simple:

<script>
  function handler() {
    alert("...");
    return false;
  }
</script>

<a href="http://w3.org" onclick="return handler()">w3.org</a>

Also we can use event.preventDefault(), like this:

<script>
  function handler(event) {
    alert("...");
    event.preventDefault();
  }
</script>

<a href="http://w3.org" onclick="handler(event)">w3.org</a>