Hide/show element with a boolean

JavascriptJqueryunderscore.jsVisibility

Javascript Problem Overview


I tend to have a lot of these in my code

if(shouldElementBeVisible)
    $element.show()
else
    $element.hide()

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

$element.showOrHideDependingOn(shouldElementBeVisible)

Javascript Solutions


Solution 1 - Javascript

Apparently you can just pass a boolean to the toggle function

$element.toggle(shouldElementBeVisible)

Solution 2 - Javascript

Yes there is!

$element.toggle();

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.

$element.toggle(display);

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

source

Solution 3 - Javascript

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

$element.toggle();

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

Solution 4 - Javascript

$element[ shouldElementBeVisible?'show':'hide' ]()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAakil FernandesView Question on Stackoverflow
Solution 1 - JavascriptAakil FernandesView Answer on Stackoverflow
Solution 2 - JavascriptZach SpencerView Answer on Stackoverflow
Solution 3 - JavascriptMikeView Answer on Stackoverflow
Solution 4 - JavascriptChristian EduardoView Answer on Stackoverflow