Skip to content

Instantly share code, notes, and snippets.

@brandonbarringer
Last active October 19, 2022 19:07
Show Gist options
  • Save brandonbarringer/e194cd67ad1f5edcf4c2811de294d52b to your computer and use it in GitHub Desktop.
Save brandonbarringer/e194cd67ad1f5edcf4c2811de294d52b to your computer and use it in GitHub Desktop.
Dismissable Alert Custom Web Component
/**
* 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') || '&times;';
}
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;
customElements.define('global-alert', GlobalAlert);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment