Main Contents

Preventing the default action in jQuery

jQuery March 23, 2010

It always feels good to find something new which moves you past the knowledge you had before. To me it feels like conquering a new step. Here is one of those: In the past I learned that to prevent an action to happen one needs to use:

return false;

Today I found something which I feel much more slick and less of an after thought to the function just run:

event.preventDefault()

This is not something new, it appears to have been added to jQuery version 1.0 (!!) but for some reason the return false; seems to be somewhat of an agreed upon standard. As can be read on the JQuery API pages for event.preventDefault():

Description: If this method is called, the default action of the event will not be triggered.

For example, clicked anchors will not take the browser to a new URL.

The following could be an example of usage:

	$("a").click(function(event) {
  		event.preventDefault();
  		alert("I did not follow that HREF link!");
	});

The sole purpose of return false; is to have browsers degrade nicely: if the user does not have javascript enabled go to the link in the anchor tag, else execute the script. This is exactly what event.preventDefault() does: if there is no javascript, no function will be triggered and thus the default action will be executed; on the other hand, if javascript is active, the default action will be prevented with this method.

 

1 Comment

  1. szaleq July 19, 2010 @ 1:30 pm

    Please, help me… Can I run prevented event later?

Leave a comment


Google Analytics Alternative