e.target
выбирает диапазон в Chrome вместо кнопки, на которой было связано событие, из-за распространения события.
Используйте e.currentTarget
вместо e.target
, он выберет кнопку, к которой событие было изначально привязано, а не какой-либо из его дочерних элементов.
// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rectangular switch
const rect = document.querySelector("#toggle-rect");
rect.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
// Rounded switch
const round = document.querySelector("#toggle-round");
round.addEventListener("click", e => {
let checked = e.currentTarget.getAttribute("aria-checked") === "true";
console.log(checked);
e.currentTarget.setAttribute("aria-checked", String(!checked));
});
/* reset button */
button {
background: none;
border: 0;
color: inherit;
padding: 0;
}
/* The switch - the box around the slider */
.switch {
position: relative;
/* display: inline-block; */
width: 60px;
height: 34px;
}
/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
/* TODO: put disable color here */
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:focus+.slider {
box-shadow: 0 0 1px #2196f3;
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
/* changing the background while toggling */
[role="switch"][aria-checked="true"] .slider {
background-color: #2196f3;
}
/* toggling the handle */
[role="switch"][aria-checked="true"] .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
<!-- Rectangular switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-rect">
<span class="slider"></span>
</button>
<!-- Rounded switch -->
<button role="switch" aria-checked="false" class="switch" id="toggle-round">
<span class="slider round"></span>
</button>