jQuery check if element is visible or hidden

Useful jQuery toggle visibility methods.

Or you may check if element is visible or hidden with jQuery. Hide or show it according to its visibility.

Test code:

html:


<div class="wrap-js-action">

    <span class="click js-action">click to show or hide (display:block|none;)</span>

</div>

<div class="target">target</div>



<div class="wrap-js-action">

    <span class="click-toggle js-action">click to show or hide by toggle (display:block|none;)</span>

</div>

<div class="target-toggle">target toggle</div>



<div class="wrap-js-action">

    <span class="click-visibility js-action">click to show or hide (visibility:hidden|visible)</span>

</div>

<div class="target-visibility">target visibility</div>



<div class="wrap-js-action">

    <span class="click-opacity js-action">click to show or hide (opacity:0|1)</span>

</div>

<div class="target-opacity">target opacity</div>

<div>last line</div>

jQuery:


$('.click').click(function () {

    if ($('.target').is(':hidden')) {

        $('.target').show();

    } else {

        $('.target').hide();

    }

});





$('.click-toggle').click(function () {

    $('.target-toggle').toggle();

});



$('.click-visibility').click(function () {

    if ($('.target-visibility').css('visibility') == 'hidden') {

        $('.target-visibility').css({

            'visibility': 'visible'

        });

    } else {

        $('.target-visibility').css({

            'visibility': 'hidden'

        });

    }

});



$('.click-opacity').click(function () {

    if ($('.target-opacity').css('opacity') == '0') {

        $('.target-opacity').css({

            'opacity': '1'

        });

    } else {

        $('.target-opacity').css({

            'opacity': '0'

        });

    }

});

css:


.js-action {

    cursor: pointer;

    border-bottom: 1px dashed #555;

}



.wrap-js-action {

    margin: 15px 0 0 0;

}

Difference between "display:none", "visibility:hidden" and "opacity:0":

  • display:none hides the element and it does not take up any space;
  • visibility:hidden hides the element, but it still takes up space in the layout;
  • opacity:0 hides the element as "visibility:hidden" and it still takes up space in the layout; the only difference is that opacity let to do element partly transparent;

Another difference between visibility:hidden and opacity:0 is that the element will still respond to events (like clicks) with opacity:0.

10 thoughts on “jQuery check if element is visible or hidden”

Leave a Comment