toggle-button.js
unknown
plain_text
2 years ago
2.4 kB
7
Indexable
const template = document.createElement('template');
template.innerHTML = `
<!-- we can link to a style sheet from our template too -->
<link rel="stylesheet" href="https://meyerweb.com/eric/tools/css/reset/reset.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fork-awesome@1.2.0/css/fork-awesome.min.css"
integrity="sha256-XoaMnoYC5TH6/+ihMEnospgm0J1PM/nioxbOUdnM8HY=" crossorigin="anonymous">
<style>
.wrapper{
display: flex;
flex-flow: column;
align-items: center;
justify-content: center;
}
.toggle{
height: 15px;
width: 15px;
border: 1px solid black;
margin: 5px auto;
}
.active{
background-color: lightgreen;
}
</style>
<div class="wrapper">
<p>label text</p>
<div class="toggle" role="button" aria-pressed="false"></div>
</div>
`
class toggle extends HTMLElement {
constructor() {
super();
//Sets the value of this instance to 0
this.value = 0;
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.shadowRoot.querySelector("p").innerHTML = this.getAttribute("label");
}
connectedCallback() {
// Creates list for all the items
const toggles = this.shadowRoot.querySelectorAll(".toggle");
//Listenter to see if the buttons are clicked
toggles.forEach((e) => {
e.addEventListener("click", () => {
//Toggles the class active for the toggle-button
e.classList.toggle("active");
//Checks if aria-pressed is false and changes it to true and sets value to 1
if (e.getAttribute("aria-pressed") === "false") {
e.setAttribute("aria-pressed", "true");
this.value = 1;
} else {
e.setAttribute("aria-pressed", "false");
this.value = 0;
};
//Custom event to bubble the value of the instance
const evt = new Event("input", { bubbles: true, detail: { e: () => this.value } })
this.dispatchEvent(evt);
});
});
}
}
window.customElements.define("toggle-button", toggle);Editor is loading...
Leave a Comment