-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtogglebutton.js
94 lines (79 loc) · 1.94 KB
/
togglebutton.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const template = document.createElement("template");
const CSS = {
slider: "slider",
sliderOn: "slider--on",
};
template.innerHTML = `
<style>
.slider {
position: absolute;
width: 20px;
height: 20px;
background-color: #808080;
border-radius: 50%;
transition-duration: 1s;
pointer-events: none;
}
.container {
width: 40px;
height: 20px;
background-color: black;
border-radius: 30% / 50%;
position: relative;
pointer-events: none;
}
.slider--on {
transform: translateX(100%);
}
.container input {
opacity: 0;
position: absolute;
pointer-events: all;
}
</style>
<div class="container">
<input type="checkbox" id="something"/>
<div
class="slider"
></div>
</div>
`;
class ToggleButton extends HTMLElement {
static get observedAttributes() {
return ["on"];
}
get on() {
this.getAttribute("on");
}
set on(value) {
this.setAttribute("on", value);
}
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.appendChild(template.content.cloneNode(true));
this.inputElement = this.shadowRoot.querySelector("input");
}
onClickListener = () => {
this.toggleButton();
};
connectedCallback() {
const radiobutton = this.shadowRoot.querySelector(`.${CSS.slider}`);
if (this.hasAttribute("on")) {
radiobutton.classList.add(CSS.sliderOn);
}
this.inputElement.addEventListener("click", this.onClickListener);
}
disconnectedCallback() {
this.inputElement.removeEventListener("click", this.onClickListener);
}
attributeChangedCallback() {
this.shadowRoot
.querySelector(`.${CSS.slider}`)
.classList.toggle(CSS.sliderOn, this.hasAttribute("on"));
}
toggleButton() {
this.toggleAttribute("on");
}
}
window.customElements.define("anveshmekala-toggle-button", ToggleButton);