Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to prevent the browser from executing the default action in jQuery?
To prevent the browser from executing the default action in jQuery, use the preventDefault() method. The preventDefault() method prevents the browser from executing the default action associated with an event, such as following a link, submitting a form, or checking a checkbox.
Example
The following example demonstrates how to prevent a link from navigating to its href destination. You can also use the method isDefaultPrevented() to know whether this method was ever called on that event object ?
<html>
<head>
<title>jQuery preventDefault() method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("a").click(function(event){
event.preventDefault();
alert("Default behavior is disabled!");
});
});
</script>
</head>
<body>
<span>Click the following link and it won't work:</span>
<a href="https://www.google.com">GOOGLE Inc.</a>
</body>
</html>
The output of the above code is ?
Click the following link and it won't work: GOOGLE Inc. When you click the link, an alert dialog displays "Default behavior is disabled!" and the browser does not navigate to Google.com.
Common Use Cases
The preventDefault() method is commonly used with:
- Links ? To prevent navigation
- Forms ? To prevent form submission for validation
- Checkboxes ? To control checking/unchecking behavior
- Keyboard events ? To disable certain key combinations
Conclusion
The preventDefault() method is essential for customizing user interactions by stopping the browser's default response to events. This allows developers to implement custom behaviors while maintaining full control over the user experience.
