<div>
<input type="checkbox" class="chek-box" id="check-1"/>
<label for="check-1" class="custom-check">1</label>
</div>
<div>
<input type="checkbox" class="chek-box" id="check-2" />
<label for="check-2" class="custom-check">2</label>
</div>
<div>
<input type="checkbox" class="chek-box" id="check-3"/>
<label for="check-3" class="custom-check">3</label>
</div>
<br>
<br>
<button type='button' data-target='#check-1'>Class 1</button>
<button type='button' data-target='#check-2'>Class 2</button>
<button type='button' data-target='#check-3'>Class 3</button>
<pre id="out"></pre>
.custom-check {
background: red;
width: 50px;
height: 50px;
color: white;
font-size: 40px;
}
.chek-box:checked ~ label{
background: green;
}
pre#out {
position: absolute;
top: 0px;
left: 250px;
height: 200px;
overflow-y: scroll;
width: 220px;
outline: dashed 1px gray;
background: #eee;
}
document.addEventListener('click', function(e) {
if (e.target.matches('button[data-target]')) {
const button = e.target;
const targetId = button.dataset.target;
const target = document.querySelector(targetId);
target.checked = !target.checked;
const event = new Event('change', { bubbles: true });
target.dispatchEvent(event);
}
});
document.addEventListener('change', function(e) {
if (e.target.matches('.chek-box')) {
const checkbox = e.target
log(`${checkbox.id} changed to ${checkbox.checked}`);
}
});
function log(msg) {
out.textContent += msg + '\n';
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.