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:

click to show or hide (display:block|none;)
target
click to show or hide by toggle (display:block|none;)
target toggle
click to show or hide (visibility:hidden|visible)
target visibility
click to show or hide (opacity:0|1)
target opacity
last line

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'
        });
    }
});
​​
.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.

6 comments on “jQuery check if element is visible or hidden

  1. Pingback: Solution: Testing if something is hidden using jQuery #dev #it #computers | Good Answer

  2. Pingback: How to: Testing if something is hidden using jQuery | Technical information for you

  3. Pingback: jquery template if block displaying extra comma in table in | User3

  4. Pingback: jquery template if block displaying extra comma in table in | user97

    1. web-developer

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

Leave a Reply

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