Stop Actions with jQuery .preventDefault()

Sam Deering
Tweet

Because the action is not followed we may need to know when the user prompted the action and can use event.isDefaultPrevented() to determine if this method has been called by an event handler that was triggered by this event. This can be used to trigger a function call. Could also be useful for dynamic URL’s with XHtmlRequest in jQuery to fetch a page with a module for example href=”index.php?page=contact instead of contact.php. You may also want to look at MOD Rewrite options which can also provide this functionality and SEO goodness. jQuery Stop Event Functions. Watch out if you’re using $(document).bind(“keydown keypress”, function(event) then e.preventDefault() won’t work try.. event.preventDefault(). Sometimes you have a hyperlink that needs to be a hyperlink but you don’t want it to process and open the link but only call a javascript function say. Fortunately there is a function in jQuery to stop the hyperlink action.

jQuery Preventdefault Function Demo

Example 1 – Prevent and catch a hyperlink click

< !DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>
</head>
<body>

<a href="http://jquery.com">default click action is prevented</a>
<div id="log"></div>

<script>
$("a").click(function(event) {
  event.preventDefault();
  $('<div></div>')
    .append('default ' + event.type + ' prevented')
    .appendTo('#log');
});
</script>

</body>
</html>

Example 2 – Prevent form submit button

$('#myform').submit(function(event) {
	event.preventDefault();
	var self = this;
	window.setTimeout(function() {
		self.submit();
	}, 2000);
});

Example 3 – Delay hyperlink target until after animation effect

$("#ELEMENT_WHICH_AFFECT_THE_SLIDEUP")
.click(function(event){
	event.preventDefault(); // prevents link to be redirected
	var time = 1000; // time for slideup effect
	var url = $(this).attr("href"); // pick url for redirecting via javascript

	$("#ELEMENT_TO_SLIDE_UP").slideUp(time); // effect
	window.setTimeout(function(){document.location.href=url;}, time); // timeout and waiting until effect is complete
	return -1;
});

Example 4 – Disable keydown scroll button

$(document).keydown(function(event){
	// Move Down
	if(event.keyCode == '40'){
		event.preventDefault();
		var posY = $('#'+selectedTxtID).css('top');
		posY = parseFloat(posY);
		var newPosY = posY + 1;
		$('#'+selectedTxtID).css('top', newPosY+'px');
	}
})

This function can also be used not only on hyperlinks but anything that has a default action you wish to prevent.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.