Event.defaultPrevented
The defaultPrevented
read-only property of the Event
interface returns a boolean value indicating whether or not the call to Event.preventDefault()
canceled the event.
Syntax
var defaultWasPrevented = event.defaultPrevented;
Value
A boolean value, where true
indicates that the default user agent action was prevented, and false
indicates that it was not.
Example
This example logs attempts to visit links from two <a>
elements. JavaScript is used to prevent the second link from working.
HTML
<p><a id="link1" href="#link1">Visit link 1</a></p> <p><a id="link2" href="#link2">Try to visit link 2</a> (you can't)</p> <p id="log"></p>
JavaScript
function stopLink(event) { event.preventDefault(); } function logClick(event) { const log = document.getElementById('log'); if (event.target.tagName === 'A') { if (event.defaultPrevented) { log.innerText = 'Sorry, but you cannot visit this link!\n' + log.innerText; } else { log.innerText = 'Visiting link...\n' + log.innerText; } } } const a = document.getElementById('link2'); a.addEventListener('click', stopLink); document.addEventListener('click', logClick);
Result
Specifications
Specification |
---|
DOM Standard (DOM) # ref-for-dom-event-defaultprevented① |
Browser compatibility
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
defaultPrevented |
18 |
12 |
6 |
9 |
11 |
5 |
≤37 |
18 |
6 |
11 |
5 |
1.0 |
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Event/defaultPrevented