[JavaScript] Cancelling the Default Action

When you attach the “click” event handler to the anchor tag, it does not prevent from navigating to  another page, which is the default behavior of the <a>. What if you want not to execute the default action?

1. window.event.returnValue

In the legacy IE, you can set the event’s “returnValue” property to false in order to prevent the default action from executing.


function onLinkClicked() {
  alert("Hello");
  window.event.returnValue = false; // do not navigate to the link
}


<a id="myLink" href="...">link</a>

This code works only in IE.

 

2. return false

Another way to prevent the default action is to return “false” from the event handler.


function onLinkClicked() {
  alert("Hello");
  return false;
}


<a id="myLink">link</a>

Or,


function onLinkClicked() {
  alert("Hello");
}


<a id="myLink">link</a>

This approach works in all major browsers.

 

3. preventDefault()

W3C recommends to use the “preventDefault()” method.

document.getElementById("myLink").onclick = onLinkClicked;

function onLinkClicked(e) {
  alert("Hello");
  e.preventDefault();
}

 

4. jQuery

jQuery’s event objects wraps the “preventDefault()” method in a browser compatible way.

$(document).ready(function () {
  $("#clickBtn1").click(onLinkClicked);
});

function onLinkClicked(e) {
  alert("Hello");
  e.preventDefault();
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s