Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active June 13, 2022 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nolanlawson/cdeff78cc96d6654b703235f93d850da to your computer and use it in GitHub Desktop.
Save nolanlawson/cdeff78cc96d6654b703235f93d850da to your computer and use it in GitHub Desktop.
Shadow dialog example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dialog element and shadow DOM</title>
<style>
body {
margin: 0 auto;
max-width: 400px;
padding: 40px;
}
</style>
</head>
<body>
<h1>Dialog element and shadow DOM</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>
<button>Light button</button>
<open-shadow></open-shadow>
<button>Another light button</button>
</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