<span id="checkbox" tabindex="0" role="checkbox" aria-checked="false" aria-labelledby="checkboxLabel"></span>
<label id="checkboxLabel">Subscribe to our updates?</label>
body {
margin: 100px;
}
#checkbox {
width: 20px;
height: 20px;
display: inline-block;
vertical-align: middle;
border-radius: 6px;
border: 1px solid gray;
}
label {
display: inline-block;
vertical-align: middle;
}
.is-checked {
background-color: #ddd;
}
View Compiled
let checkboxEl = document.getElementById('checkbox');
let labelEl = document.getElementById('checkboxLabel');
labelEl.onclick = function handleLabelClick() {
checkboxEl.focus();
toggleCheckbox();
}
function toggleCheckbox() {
let isChecked = checkboxEl.classList.contains('is-checked');
checkboxEl.classList.toggle('is-checked', !isChecked);
checkboxEl.setAttribute('aria-checked', !isChecked);
}
checkboxEl.onclick = function handleClick() {
toggleCheckbox();
}
checkboxEl.onkeypress = function handleKeyPress(event) {
let isEnterOrSpace = event.keyCode === 32 || event.keyCode === 13;
if(isEnterOrSpace) {
toggleCheckbox();
}
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.