Using and Styling the Dialog Element | CSS-Tricks
Wasn’t it great — nay, amazing – the day we got a native HTML <dialog> element? It’s, what now, nearly ten years old? Even so, I always find myself looking up how it works, when to use it, ideas for styling it, and whatnot. There’s a lot of nuance to this seemingly little piece of web architecture and it’s high time I give it a proper look… for future Geoff, but maybe future you as well.
<button id="dialog-button">Open Dialog</button>
<dialog id="dialog">...</dialog>
It won’t open by default. We could manually set the open attribute:
<dialog id="dialog" open>...</dialog>
But when do you ever want to open a dialog by default? I’m sure it’s a rare use case. Instead, we have a JavaScript show() method for that. We can set up variables for the dialog and button, then invoke the method:
const dialogButton = document.querySelector('#dialog-button');
const dialog = document.querySelect('#dialog');
formButton.addEventListener('click', () => {
That works, but buyer beware — that treats the dialog as more of a pop-up than a modal, and modal is what I think you’ll want in most cases. The key differences? A modal includes a backdrop, is automatically positioned in the center of the page, and allows the Esc key to close it.
Notice how show() lacks the backdrop, positioning, and closing stuff:
So, maybe invoke the showModal() method instead:
const dialogButton = document.querySelector('#dialog-button');
const formDialog = document.querySelector('#dialog');
<button id="dialog-button">Open Dialog</button>
<dialog id="dialog">...</dialog>
It won’t open by default. We could manually set the open attribute:
<dialog id="dialog" open>...</dialog>
But when do you ever want to open a dialog by default? I’m sure it’s a rare use case. Instead, we have a JavaScript show() method for that. We can set up variables for the dialog and button, then invoke the method:
const dialogButton = document.querySelector('#dialog-button');
const dialog = document.querySelect('#dialog');
formButton.addEventListener('click', () => {
That works, but buyer beware — that treats the dialog as more of a pop-up than a modal, and modal is what I think you’ll want in most cases. The key differences? A modal includes a backdrop, is automatically positioned in the center of the page, and allows the Esc key to close it.
Notice how show() lacks the backdrop, positioning, and closing stuff:
So, maybe invoke the showModal() method instead:
const dialogButton = document.querySelector('#dialog-button');
const formDialog = document.querySelector('#dialog');
Kategori:
Go ve Rust
Bu konuyu EL11.Net forumunda tartışmak ister misiniz?
Forumda Gör