custom checkboxes with excellent browser support
Excellent code for making checkboxes functional in all browsers with easy to understand formatting and css code. May even work in IE8 although I haven't tested it yet.
by William Green
February 11, 2020
HTML
<h1>Javascript, html, and css checkboes</h1>
<h3>Normal checkbox</h3>
<div id="checkboxOne" class="checkbox">
<div class="checkboxDot"></div>
<input type="button" value="Item 1">
</div>
<div id="checkboxOneStatus"></div>
<input type="button" class="valueButton" onclick="document.getElementById('checkboxOneStatus').innerHTML = document.getElementById('checkboxOne').getAttribute('data-checked');" value="Is it checked?">
<h3>Checked by default</h3>
<div id="checkboxTwo" class="checkbox" data-checked="true">
<div class="checkboxDot"></div>
<input type="button" value="Item 2">
</div>
<div id="checkboxTwoStatus"></div>
<input type="button" class="valueButton" onclick="document.getElementById('checkboxTwoStatus').innerHTML = document.getElementById('checkboxTwo').getAttribute('data-checked');" value="Is it checked?">
CSS
/*IMPORTANT STYLES... THE STYLES LATER ARE NOT DIRECTLY RELATED THE THE CHECKBOXES*/
.checkbox {
background-color:#eee;
border-radius:3px;
padding:5px;
display:table;
}
.checkbox input {
outline:none;
border:0;
background-color:transparent;
display:inline-block;
vertical-align:middle;
}
/*.checkbox .checkboxDot*/[data-checked="false"] {
background-color:transparent;
border:1px solid #000;
display:inline-block;
vertical-align:middle;
width:16px;
height:16px;
border-radius:50%;
-o-transition:all .5s ease;
-moz-transition:all .5s ease;
-webkit-transition:all .5s ease;
-ms-transition:all .5s ease;
transition:all .5s ease;
}
/*.checkbox .checkboxDotActive*/ .checkbox [data-checked="true"] {
background-color:#01A1DB;
border:1px solid transparent;
display:inline-block;
vertical-align:middle;
width:16px;
height:16px;
border-radius:50%;
-o-transition:all .5s ease;
-moz-transition:all .5s ease;
-webkit-transition:all .5s ease;
-ms-transition:all .5s ease;
transition:all .5s ease;
}
/*END IMPORTANT STYLES*/
/*START IRRELEVANT STYLES*/
.valueButton {
margin-top:10px;
}
/*END IRRELEVANT STYLES*/
JavaScript
window.addEventListener("load",function(){
var checkboxes = document.getElementsByClassName('checkbox');
for (var i = 0; i != checkboxes.length; i++) {
if (checkboxes[i].hasAttribute('data-checked') == false) {
checkboxes[i].setAttribute('data-checked', 'false');
} else {
if (checkboxes[i].getAttribute('data-checked') == 'true') {
checkboxes[i].setAttribute('data-checked', 'true');
checkboxes[i].children[0].className = 'checkboxDotActive';
}
}
checkboxes[i].addEventListener('click',function(){
if (this.getAttribute('data-checked') == 'true') {
this.setAttribute('data-checked', 'false');
this.children[0].className = 'checkboxDot';
} else {
this.setAttribute('data-checked', 'true');
this.children[0].className = 'checkboxDotActive';
}
};
}
};