Home > Back-end >  Cannot close <dialog> element with display set to grid
Cannot close <dialog> element with display set to grid

Time:03-29

The HtmlDialogElement.close() function seems to have no effect on a <dialog> element when that dialog has its display style set to grid.

Does anyone happen to know why? Note that removing the display: grid allow the dialog to function correctly. I have seen this behavior on the latest versions of both Chrome and Firefox.

See minimum reproduction below. If you prefer, here's a Codepen: https://codepen.io/ChristianMay/pen/MWrmdzJ

let dialog = document.querySelector('dialog')
let closeButton = document.querySelector("#dialog-close");
closeButton.addEventListener('click', () => {
  dialog.close();
})
dialog {
  display: grid;
}
<dialog  open="">
  Test
</dialog>

<button id="dialog-close">Close dialog</button>

CodePudding user response:

The dialog is considered to be open (or shown) if the attribute open is present.

Once this attribute is not present, the dialog is hidden. I suppose that setting the display to grid overrides the default styling for dialog, which should hide the dialog whenever open is removed. We could restore this behavior by adding styling to the dialog without open attribute.

let dialog = document.querySelector('dialog')
let closeButton = document.querySelector("#dialog-close");
closeButton.addEventListener('click', () => {
   dialog.close();
})
dialog:not([open]){
  display:none;
}


dialog{
  display:grid;
}
<dialog  open="">
  Test
</dialog>

<button id="dialog-close">Close dialog</button>

  • Related