jQuery check if element is visible or hidden

You can check easier method with jQuery toggle visibility.

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

Test code:

<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>

"display:block|none" method:

$('.click').click(function() {
    if ($('.target').is(':hidden')) {
        $('.target').show();
    } else {
        $('.target').hide();
    }
});

Same as prev:

$('.click').click(function() {
    if ($('.target').is(':visible')) {
        $('.target').hide();
    } else {
        $('.target').show();
    }
});

Same as prev, but shorter:

$('.click-toggle').click(function() {
    $('.target-toggle').toggle();
});

"visibility:hidden|visible" method:

$('.click-visibility').click(function() {
    if ($('.target-visibility').css('visibility') == 'hidden'){
        $('.target-visibility').css({visibility: "visible", display: ""});
    }else{
        $('.target-visibility').css({visibility: "hidden", display: ""});
    }
});

"opacity:0|1" method:

$('.click-opacity').click(function() {
    if ($('.target-opacity').css('opacity') == '0'){
        $('.target-opacity').css({'opacity': '1', display: ''});
    }else{
        $('.target-opacity').css({'opacity': '0', display: ''});
    }
});

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;
VN:F [1.9.17_1161]
Rating: 0 (from 0 votes)

2 thoughts on “jQuery check if element is visible or hidden

    • thanks for feedback,
      I've updated article by adding "visibility:hidden" and "opacity:0" examples.

      VN:F [1.9.17_1161]
      Rating: 0 (from 0 votes)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">