Hide/show element with a boolean


Hide/show element with a boolean

I tend to have a lot of these in my code

Is there any more elegant way packaged with javascript, jquery, or underscore? Ideally I want something that looks like this


Solution 1:

Apparently you can just pass a boolean to the toggle function


Solution 2:

Yes there is!


Without any parameters, toggle just toggles the elements visibility (I don’t mean the visibility property) and depends on the current state of the element.


If you call toggle with a boolean parameter, element is shown if it is true and hidden if it is false


Solution 3:

jQuery has toggle: http://api.jquery.com/toggle/


This will show the element if it’s hidden, and hide it if it’s shown.

Solution 4:

The function .toggle() changes the display of the element.

If you want to change visibility, instead, I’d suggest using the ?: operator. For this, on your CSS, set the visibility to the original state, and in the JS simply put:

    var checkboxChecked = $("#yourCheckbox").(":checked");

    $("#yourElement").css("visibility", checkboxChecked ? "visible" : "hidden");