Last active
October 19, 2022 19:07
-
-
Save brandonbarringer/e194cd67ad1f5edcf4c2811de294d52b to your computer and use it in GitHub Desktop.
Dismissable Alert Custom Web Component
This file contains hidden or 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
/** | |
* Attributes: | |
* close-icon: String | |
* | |
* Example: | |
* <global-alert> | |
* <h2>This is a title</h2> | |
* <p>This is a paragraph</p> | |
* </global-alert> | |
*/ | |
class GlobalAlert extends HTMLElement { | |
get hidden() { | |
return this.hasAttribute('hidden'); | |
} | |
get contents() { | |
return this.innerHTML; | |
} | |
get closeIcon() { | |
return this.getAttribute('close-icon') || '×'; | |
} | |
show() { | |
const storeVal = window.localStorage.getItem('globalAlert'); | |
if (storeVal !== this.contents || !storeVal) { | |
this.removeAttribute('hidden'); | |
this.dispatchEvent(new CustomEvent('globalAlert:open')); | |
} | |
} | |
hide() { | |
this.setAttribute('hidden', ''); | |
this.dispatchEvent(new CustomEvent('globalAlert:close')); | |
window.localStorage.setItem('globalAlert', this.contents); | |
} | |
connectedCallback() { | |
this.innerHTML = ` | |
<style> | |
global-alert { | |
position: relative; | |
} | |
</style> | |
${this.contents} | |
<button class="global-alert__close" aria-label="Close"> | |
${this.closeIcon} | |
</button> | |
`; | |
this.querySelector('.global-alert__close').addEventListener('click', () => { | |
this.hide(); | |
}); | |
this.show(); | |
} | |
} | |
export default GlobalAlert; |
This file contains hidden or 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
customElements.define('global-alert', GlobalAlert); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment