I have added an click event to the class sec which will show and hide the checkbox.
But when I click on checkbox, then checkbox hides.
let sec = document.querySelector('.sec');
let checkbox = document.querySelector('.switch');
sec.addEventListener('click', ()=>{
checkbox.classList.toggle("show");
})
.sec{
background:lightgray;
padding:10px;
width:450px;
cursor:pointer;
position:relative;
margin-top:70px;
}
.switch{
display:none;
background:gray;
padding:5px;
position:absolute;
bottom : 100%
}
.switch::after {
content: '';
position: absolute;
top: 100%;
left: calc(50% - 10px);
background: #88b7d5;
background: #242334;
border: 1px solid #3F3E5B;
width: 10px;
height: 10px;
-webkit-clip-path: polygon(0 0, 100% 0, 50% 100%);
clip-path: polygon(0 0, 100% 0, 50% 100%);
}
.show{
display:block;
}
<section class="sec">
<p>Click me to show popup</p>
<div class="popup">
<label class="switch">
I am checkbox
<input type="checkbox">
</label>
</div>
</section>
The click on the checkbox is also a click on the section because the checkbox is inside the section, so the event listener is toggling the checkbox.
Add an event listener on the checkbox label that uses event.stopPropagation() to prevent the event from bubbling to the container.
let sec = document.querySelector('.sec');
let label = document.querySelector('.switch');
sec.addEventListener('click', () => {
label.classList.toggle("show");
})
label.addEventListener('click', (event) => {
event.stopPropagation()
})
.sec {
background: lightgray;
padding: 10px;
width: 450px;
cursor: pointer;
position: relative;
margin-top: 70px;
}
.switch {
display: none;
background: gray;
padding: 5px;
position: absolute;
bottom: 100%
}
.switch::after {
content: '';
position: absolute;
top: 100%;
left: calc(50% - 10px);
background: #88b7d5;
background: #242334;
border: 1px solid #3F3E5B;
width: 10px;
height: 10px;
-webkit-clip-path: polygon(0 0, 100% 0, 50% 100%);
clip-path: polygon(0 0, 100% 0, 50% 100%);
}
.show {
display: block;
}
<section class="sec">
<p>Click me to show popup</p>
<div class="popup">
<label class="switch">
I am checkbox
<input type="checkbox">
</label>
</div>
</section>