Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active Jun 13, 2022
Embed
What would you like to do?
Shadow dialog example - first element is closed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dialog element and shadow DOM - first element is closed</title>
<style>
body {
margin: 0 auto;
max-width: 400px;
padding: 40px;
}
</style>
</head>
<body>
<h1>Dialog element and shadow DOM - first element is closed</h1>
<p>Browser supports <code>&lt;dialog&gt;</code>? <span id="supports"></span></p>
<p>Tab around with the keyboard, use Esc to close the dialog.</p>
<button>Focusable button</button>
<button class="modal-button">Click to open modal dialog</button>
<button>Another focusable button</button>
<dialog>
<div>
<closed-shadow></closed-shadow>
<button>Light button</button>
<open-shadow></open-shadow>
</div>
<video controls src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm"></video>
<div>
<button>Light button</button>
<closed-shadow></closed-shadow>
<button>Another light button</button>
</div>
</dialog>
<script>
document.querySelector('#supports').textContent = typeof HTMLDialogElement === 'function' ? 'Yes' : 'No'
function addStyle(root) {
const css = `
button:focus {
outline: 4px dashed blue;
outline-offset: -2px;
}
button {
font-size: 1.2em;
padding: 5px;
margin: 5px;
}`
const style = document.createElement('style')
style.textContent = css
root.appendChild(style)
}
class ClosedShadow extends HTMLElement {
constructor () {
super()
const shadow = this.attachShadow({ mode: 'closed' })
shadow.innerHTML = '<button>Closed shadow button!</button>'
addStyle(shadow)
}
}
class OpenShadow extends HTMLElement {
constructor () {
super()
const shadow = this.attachShadow({ mode: 'open' })
shadow.innerHTML = '<button>Open shadow button!</button>'
addStyle(shadow)
}
}
customElements.define('closed-shadow', ClosedShadow)
customElements.define('open-shadow', OpenShadow)
document.querySelector('.modal-button').addEventListener('click', () => {
document.querySelector('dialog').showModal()
})
addStyle(document.head)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment