Please enable Javascript for better experience...
jQuery event.preventDefault() and event.isDefaultPrevented() Method
By Big | Aug 18, 2015 | In Tips | Total Views [ 870 ]
Taged In
(0 Like)
Rate

JQuery methods event.preventDefault() and event.isDefaultPrevented() can be used to prevent default action of that element.

Introduction

If you are using a tag and your client say that it should not perform navigation or if you are using a button and you think, it should not perform click event, then JQeury has a solution for you. Simply use event.preventDefault() to prevent default action behavior and event.isDefaultPrevented() to check if your changes are applied or not.

event.preventDefault()

Below is the use of preventDefault() method. I am applying it on a tag and it will not let it navigate to desired url.

$("a").click(function(event){
event.preventDefault();
});

event.isDefaultPrevented()

Below is the use of isDefaultPrevented() method. It will check if changes applied or not.

$("a").click(function(event){
    event.preventDefault();
    alert("Is preventDefault() applied: " + event.isDefaultPrevented());
});

HTML

Here is the sample code.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").click(function(event){
event.preventDefault();
console.log(event.isDefaultPrevented());
});
});
</script>
</head>
<body>
<a href="http://dotnet-concept.com/">Dot Net Concept</a>
<p>The preventDefault() method will prevent the link to navigate to the URL and isDefaultPrevented() method tells that change has been applied successfully.</p>
</body>
</html>

Hope it helps you.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment