preventDefault() event method
Definition and Usage
If the event is cancelable, the preventDefault() method will cancel the event, which means that the default operation of the event will not occur.
For example, it is useful in the following situations:
- Click the "Submit" button to prevent the form from being submitted
- Click the link to prevent the link from following the URL
Note:Not all activities can be canceled. Please use Cancelable property to determine whether the event is cancelable.
Note:The preventDefault() method does not prevent the event from further propagating through the DOM. Please use stopPropagation() method to solve this.
Example
Example 1
Prevent the URL from opening the link:
document.getElementById("myAnchor").addEventListener("click", function(event){ event.preventDefault(); );
Example 2
Prevent the default operation of the checkbox:
document.getElementById("myCheckbox").addEventListener("click", function(event){ event.preventDefault(); );
grammar
event.preventDefault()
Parameters
None.
Technical Details
Return Value: | No Return Value. |
---|---|
DOM Version: | DOM Level 2 Events |
Browser Support
The numbers in the table indicate the first browser version that fully supports this method.
Methods | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
preventDefault() | Support | 9.0 | Support | Support | Support |