Toggle display of an element with plain Javascript

24 Jan 2017 in Javascript

This little snippet shows how to toggle the display of a div element by toggling the state of a checkbox:

<input type="checkbox" id="my_checkbox"/>
<div id="my_div">
    <!-- with some content inside, you know, lorem ipsum and stuff -->
</div>
<script>
    (function () {
        var checkbox = document.getElementById("my_checkbox");
        var container = document.getElementById("my_div");
        var fn = function () {
            if (checkbox.checked) {
                 // or instead of "display" you may use
                 // "visibility" with hidden/visible values
                container.style.display = "block";
            } else {
                container.style.display = "none";
            }
        };
        // set onclick handler of checkbox to the fn
        checkbox.onclick = fn;
        // call fn with checkbox scope
        fn.apply(checkbox); // or fn.call(checkbox);
    }());
</script>

Simple vanilla js.