Example
Prevent a link from opening the URL:
document.getElementById("myAnchor").addEventListener("click",
function(event){
event.preventDefault()
});
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.
For example, this can be useful when:
- Clicking on a "Submit" button, prevent it from submitting a form
- Clicking on a link, prevent the link from following the URL
Note: Not all events are cancelable. Use the cancelable property to find out if an event is cancelable.
Note: The preventDefault() method does not prevent further propagation of an event through the DOM. Use the stopPropagation() method to handle this.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
preventDefault() | Yes | 9.0 | Yes | Yes | Yes |
Syntax
event.preventDefault()
Parameters
None |
Technical Details
Return Value: | No return value |
---|---|
DOM Version: | DOM Level 2 Events |
More Examples
Example
Prevent the default action of a checkbox:
document.getElementById("myCheckbox").addEventListener("click",
function(event){
event.preventDefault()
});
Try it Yourself »
< Event Object