Using JQuery preventDefault() Method
When we are using jquery preventDefault() method then the normal action belonging to the event will never be activated or triggered.whenever we click on a anchor link, the browser navigates to a new page. This particular action is not really an event handler, however this is actually the default activity for a click on a hyperlink component.
In the same way, even though the user is actually editing or modifying a form, if the Enter key is pressed , then the submit event of the form is triggered.
If you find these default behaviors produce undesirable results then simply by calling the .preventDeafult() method it is possible to stop the event prior to the default action will be triggered. You will find it is useful to call preventDefault() method based on the condition of the event environment. For example, while in a form submission we may want to make sure that all required or necessary fields are filled in, if they are not then prevent the default action of the form element.
jquery preventdefault example
In this below example you can see, we are using preventDefault() method to the anchor texts to override the default action of the anchor text. Normally by clicking the anchor text the browser will take us to the new URL given within the anchor text. So in the below example if you click the anchor text, it won’t navigate the browser to the given URL.
<html>
<head>
<title>JQuery preventDefault Tutorial</title>
<style type="text/css">
.highlight{
background: orange;
}
body{
width: 200px;
}
</style>
<script src="jquery-1.8.3.js"></script>
<script>
$(function(){
$('a').click(function(event){
event.preventDefault();
});
});
</script>
</head>
<body>
<a href="www.google.com">Google</a>
</body>
</html>
Try the below jquery preventdefault working demo
Another Way of achieving jquery preventdefault Method
In this below example you can see, we are using return false; statement to achieve the exact above result instead of using jquery preventDefault.
<html>
<head>
<title>JQuery preventDefault Tutorial</title>
<style type="text/css">
.highlight{
background: orange;
}
body{
width: 200px;
}
</style>
<script src="jquery-1.8.3.js"></script>
<script>
$(function(){
$('a').click(function(event){
return false;
});
});
</script>
</head>
<body>
<a href="www.google.com">Google</a>
</body>
</html>
Try this Second jquery preventdefault working demo
In this JQuery tutorial, we have looked at some of the very important methods in the Event. we have seen about how to use jquery preventDefault() method to stop the default behavior of the anchor text event. Google+
VimalTuts Code Junction