HTMLElement: cancel イベント

cancel イベントは <input> および <dialog> 要素で発行されます。このイベントは、ユーザーが Esc キーで現在開いているダイアログを閉じてキャンセルしたときに発行されます。また、file 入力欄 では、ユーザーが Esc キーやキャンセルボタンでファイルピッカーダイアログをキャンセルしたときや、前回選択したファイルを再度選択したときにも発行されます。

このイベントはバブリングしません。

<dialog>Esc キーで閉じられたとき、cancel イベントと close イベントの両方が発生します。

構文

このイベント名を addEventListener() などのメソッドで使用するか、イベントハンドラープロパティを設定するかしてください。

js
addEventListener("cancel", (event) => {});

oncancel = (event) => {};

イベント型

一般的な Event です。

ダイアログのキャンセル

HTML

html
<dialog class="example-dialog">
  <button class="close" type="reset">閉じる</button>
</dialog>

<button class="open-dialog">ダイアログを開く</button>

<div class="result"></div>

JavaScript

js
const result = document.querySelector(".result");

const dialog = document.querySelector(".example-dialog");

dialog.addEventListener("cancel", (event) => {
  result.textContent = "dialog was canceled";
});

const openDialog = document.querySelector(".open-dialog");
openDialog.addEventListener("click", () => {
  if (typeof dialog.showModal === "function") {
    dialog.showModal();
    result.textContent = "";
  } else {
    result.textContent = "The dialog API is not supported by this browser";
  }
});

const closeButton = document.querySelector(".close");
closeButton.addEventListener("click", () => {
  dialog.close();
});

結果

input 要素のキャンセル

HTML

html
<label for="file">ファイルを選択したり、しなかったりしてください。</label>
<input type="file" id="file" name="file" />

<div id="result"></div>

JavaScript

js
const elem = document.getElementById("file");

const result = document.getElementById("result");

elem.addEventListener("cancel", () => {
  result.textContent = "キャンセルされました。";
});

elem.addEventListener("change", () => {
  if (elem.files.length == 1) {
    result.textContent = "ファイルが選択されました。";
  }
});

結果

ファイルセレクターを開き、選択ダイアログをエスケープキーまたはキャンセルボタンで閉じます。どちらも cancel イベントが発生します。また、マシンのローカルファイルを選択し、ファイル選択ウィンドウを再度開いて同じファイルを再選択してみてください。これも cancel イベントが発生します。

仕様書

No specification found

No specification data found for api.HTMLElement.cancel_event.
Check for problems with this page or contribute a missing spec_url to mdn/browser-compat-data. Also make sure the specification is included in w3c/browser-specs.

ブラウザーの互換性

BCD tables only load in the browser

関連情報