Last active
June 11, 2024 16:01
-
-
Save cferdinandi/813b8d599c98e68a4dd4616f9cc545ed to your computer and use it in GitHub Desktop.
How to build a show-hide Web Component. Watch the tutorial: https://youtu.be/HgI03y6DYoI
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> | |
<show-hide> | |
<button trigger hidden>Press Me</button> | |
<div content> | |
<p>🦄</p> | |
</div> | |
</show-hide> | |
<script> | |
customElements.define('show-hide', class extends HTMLElement { | |
/** | |
* Instantiate our Web Component | |
*/ | |
constructor () { | |
// Inherit parent class properties | |
super(); | |
// Define properties on our Web Component | |
this.trigger = this.querySelector('[trigger]'); | |
this.content = this.querySelector('[content]'); | |
if (!this.trigger || !this.content) return; | |
// Setup the UI | |
this.trigger.removeAttribute('hidden'); | |
this.trigger.setAttribute('aria-expanded', false); | |
this.content.setAttribute('hidden', ''); | |
// Listen for click events | |
this.trigger.addEventListener('click', this); | |
} | |
/** | |
* Handle click events | |
* @param {Event} event The event object | |
*/ | |
handleEvent (event) { | |
// Stop the button from submitting forms | |
event.preventDefault(); | |
// If the content is visible, 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'); | |
} | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment