9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

HTMLのdialog要素の背景をクリックしてdialog要素を閉じる方法

Last updated at Posted at 2022-06-29

IE11のサポートが終了して遂に色々なタグが自由に使えるようになってきました。
今まで使いたくても対応が面倒なので全部divにしていた要素の一つ、dialog要素を実装していて::backdropの部分をクリックして閉じるにはどうすればいいのか調べた際のメモです。

やりかた

dialog要素がクリックされた際、getBoundingClientRectでdialog要素の寸法を調べ、クリックされた位置がdialog要素の内か外かをチェックし、要素外ならclose()を発動させる。

const dialog = document.getElementsByTagName("dialog")[0];
const button = document.getElementsByTagName("button")[0];
button.addEventListener("click", (event) => {
  dialog.showModal();
});
dialog.addEventListener("click", (event) => {
  const rect = dialog.getBoundingClientRect();
  const inDialog =
    rect.top <= event.clientY &&
    event.clientY <= rect.top + rect.height &&
    rect.left <= event.clientX &&
    event.clientX <= rect.left + rect.width;
  if (!inDialog) {
    dialog.close();
  }
});

DEMO

See the Pen Untitled by ONSEN (@TaroTsujimoto) on CodePen.

9
8
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?