Last active
June 13, 2022 14:10
-
-
Save nolanlawson/8a5e766e53c39a484a39a346a9150b6d to your computer and use it in GitHub Desktop.
Shadow dialog example - first element is closed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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><dialog></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