Using a hidden checkbox to create styles with states – for instance when animating dropdowns, custom checkboxes, etc – is a very popular technique. It’s also very easy to do the same using JavaScript.
Are there any drawbacks to either strategy? I’m looking for differences in performance, rendering/repainting/reflow, compatibility, code standards, SEO, etc.
function toggle() {
var cb = document.getElementById('checkbox-js');
if (cb.className === 'checkbox') {
cb.className = "checkbox checked";
} else {
cb.className = "checkbox";
}
}
input[type="checkbox"] {
display: none;
}
.checkbox {
display: inline-block;
font-size: 20px;
border: 1px solid #AAA;
width: 32px;
height: 32px;
line-height: 32px;
vertical-align: middle;
}
.checkbox:before {
width: 32px;
height: 32px;
content: "x";
color: white;
text-align: center;
display: inline-block;
}
input[type="checkbox"]:checked + .checkbox:before {
color: #333;
}
.checkbox.checked:before {
color: #333;
}
<div class="css-only">
<label>
CSS Only:
<input placeholder="Name" type="checkbox" />
<span class="checkbox"></span>
</label>
</div>
<br>
<br>
<br>
<div class="with-js">
<label>
With JS:
<span onClick="toggle()" class="checkbox" id="checkbox-js"></span>
</label>
</div>
2
Answers
Of course there is.
A Checkbox is :
<input type='checkbox' />
Inputs are being submitted back to the server .
So you can read their values. This is how html works.
Using a
span
provides nothing in this manner.I interpret this questions as: should you keep your state in the DOM or in JavaScript?
Both solutions work but which is better has to do with complexity. If all you’re doing is toggling the state of a checkbox I’d say either approach is fine. Keep in mind that any interaction with the DOM is slow, but one or two repaints on a checkbox isn’t going to be a problem.
If your model and logic becomes more complex keeping the state in JavaScript might be a better approach. For instance: you have a list of checkboxes and you can only check 4.