Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate CSS ::backdrop behind HTML <dialog>?

The <dialog> element is now cross-browser compatible (since March 2022).

I tried my hand at it today and familiarised myself with:

  • HTML

    • <dialog>
  • JavaScript

    • .show()
    • .showModal()
    • .close()
  • CSS

    • ::backdrop

Everything seems straightforward but the one thing I've been unable to achieve so far is: fading up the backdrop.

For instance, if I want the final color of the backdrop to be:

  • background-color: rgba(0, 0, 63, 0.8);

but have it transition (or animate) to that background-color from:

  • background-color: rgba(0, 0, 0, 0);

is this even possible?


Here is my (non-working) example:

const myButton = document.querySelector('button');
const myDialog = document.querySelector('dialog');

const requestDialog = () => {
  myDialog.showModal();
  setTimeout(() => myDialog.classList.add('fadeUp'), 400);
}

myButton.addEventListener('click', requestDialog, false);
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 180px;
}

button {
  position: absolute;
  top: 6px;
  left: 6px;
  cursor: pointer;
}

dialog::backdrop {
  background-color: rgba(0, 0, 0, 0);
  transition: backgroundColor 0.6s ease-out;
}

dialog.fadeUp::backdrop {
  background-color: rgba(0, 0, 63, 0.8);
}
<button type="button">Click me to<br />Request Dialog</button>

<dialog>
  <h2>My Dialog</h2>
</dialog>
like image 913
Rounin - Glory to UKRAINE Avatar asked Feb 07 '26 07:02

Rounin - Glory to UKRAINE


1 Answers

I was having the same problem but this solved to me.

const dialog = document.querySelector('.modal')

function openModal() {
  dialog.showModal(); // default dialog method
}

function closeModal() {
  dialog.classList.add('close'); // run animation here
  
  dialog.addEventListener('animationend', () => {
    dialog.classList.remove('close')
    dialog.close(); // then run the default close method
  }, {once : true}); // add this to prevent bugs when reopening the modal
}
.modal {
  display: none;
}
/* when the dialog is open by its default method it adds a open tag on the element */
.modal[open] {
  display: flex;
}

.modal[open]::backdrop {
  animation: backdrop-fade 2s  ease forwards;
}

.modal.close::backdrop {
  animation: backdrop-fade 3s ease backwards;
  animation-direction: reverse;
}

@keyframes backdrop-fade {
  from {
    background: transparent;
  }
  to{
    background: rgba(0,0,0);
  }
}
<button onclick="openModal()">open modal</button>
<dialog class="modal">
    <button onclick="closeModal()">close modal</button>
</dialog>
like image 166
Adriano Avatar answered Feb 08 '26 23:02

Adriano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!