-
-
Save cferdinandi/09f8839c264162fa4d3c3191b315b957 to your computer and use it in GitHub Desktop.
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> | |
<head> | |
<title>Show/Hide</title> | |
<style type="text/css"> | |
body { | |
margin: 1em auto; | |
max-width: 30em; | |
width: 88%; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>Show/Hide</h1> | |
<show-hide> | |
<button trigger hidden>Show Content</button> | |
<div content> | |
<p>Now you see me, now you don't!</p> | |
</div> | |
</show-hide> | |
<script> | |
customElements.define('show-hide', class extends HTMLElement { | |
/** | |
* Instantiate the Web Component | |
*/ | |
constructor () { | |
// Get parent class properties | |
super(); | |
// Get the elements | |
this.trigger = this.querySelector('[trigger]'); | |
this.content = this.querySelector('[content]'); | |
if (!this.trigger || !this.content) return; | |
// Setup default UI | |
this.trigger.removeAttribute('hidden'); | |
this.trigger.setAttribute('aria-expanded', false); | |
this.content.setAttribute('hidden', ''); | |
// Create the event handler | |
this.handler = this.createHandler(); | |
} | |
/** | |
* Create the event handler | |
*/ | |
createHandler () { | |
return (event) => { | |
// Don't let the button trigger other actions | |
event.preventDefault(); | |
// If the content is expanded, hide it | |
// Otherwise, show it | |
if (this.trigger.getAttribute('aria-expanded') === 'true') { | |
this.trigger.setAttribute('aria-expanded', false); | |
this.content.setAttribute('hidden', ''); | |
} else { | |
this.trigger.setAttribute('aria-expanded', true); | |
this.content.removeAttribute('hidden'); | |
} | |
}; | |
} | |
/** | |
* Start listening to clicks | |
*/ | |
connectedCallback () { | |
if (!this.trigger || !this.content) return; | |
this.trigger.addEventListener('click', this.handler); | |
} | |
/** | |
* Stop listening to clicks | |
*/ | |
disconnectedCallback () { | |
this.trigger.removeEventListener('click', this.handler); | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment