How do I check if an element is hidden in jQuery?

6 939

841

It is possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle().

How would you test if an element is visible or hidden?

Philip Morton

Posted 2008-10-07T13:03:18.057

Reputation: 54 552

32

It's worth mentioning (even after all this time), that $(element).is(":visible") works for jQuery 1.4.4, but not for jQuery 1.3.2, under Internet Explorer 8. This can be tested using Tsvetomir Tsonev's helpful test snippet. Just remember to change the version of jQuery, to test under each one.

– Reuben – 2011-02-01T03:57:34.637

This is related although a different question: http://stackoverflow.com/questions/17425543/difference-between-hidden-and-notvisible-in-jquery/17426800#17426800

– Mark Schultheiss – 2016-03-22T19:20:54.953

1What is your definition of hidden? – fabspro – 2018-05-19T07:29:38.627

Answers

8 568

Since the question refers to a single element, this code might be more suitable:

// Checks css for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible"); 

// The same works with hidden
$(element).is(":hidden"); 

Same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ

Tsvetomir Tsonev

Posted 2008-10-07T13:03:18.057

Reputation: 89 142

41I actually found that the reverse logic words better: !$('selector').is(':hidden'); for some reason. Worth a try. – Kzqai – 2012-01-05T15:36:15.533

12

Here's a simple benchmark testing is() against regexp:http://jsperf.com/jquery-is-vs-regexp-for-css-visibility. Conclusion: if you're out for performance, use regexp over is() (since is() looks for all hidden nodes first before looking at the actual element).

– Max Leske – 2012-06-22T14:12:11.627

Tchalvak, you may feel something is right, but try to explain why. Double negation is confusing as opposed to simple statement, so $('selector').is(':shown'); is much clearer than !$('selector').is(':hidden'); – Lamy – 2012-09-10T09:43:43.313

@TsvetomirTsonev, to check the parent's visibility, you can use $(element).parent().is(":visible"); I know this is bit old, but will useful for new search – Robin Michael Poothurai – 2012-10-23T08:43:11.657

What does $(element).is(":visible") return, if the element is visible in terms of not having display:none or visibility:hidden, but the user scrolled down so he doesn't actually see it? Is there a simple way to check that? – Martin Thoma – 2013-01-02T21:30:44.700

For other users wondering if this really does work in IE7, this might save you some time - it works, jquery 1.9.1: http://imgur.com/uKD4t8h

– Chris Moschini – 2013-03-27T23:02:55.787

@MaxLeske - I'm pretty sure it's a GIVEN! (most of the time) that when you pull out the regexp knife that you'll take a perf. hit. The extra checks will be nil compared to the overhead/processing of regexp. – Bill Ortell – 2013-04-17T13:51:27.757

How do you do the inverse of this? – Sevenearths – 2013-08-30T11:46:09.363

1

I found this informative when looking up about :visible and :hidden. Essentially, it looks at the offsetHeight and offsetWidth allowing it to provide the best coverage (eg. you might have a class which has display:none; as a property and it will correctly report whether it is visible)

– Turnerj – 2013-10-17T01:53:01.187

So, should we use .is(":invisible") for false? Or !$(element).is(":visible"), or just what? – Wolfpack'08 – 2013-12-04T01:58:12.237

@Wolfpack'08: I'm looking for a similar solution as well. So far I've been using $(element).css('display')=='none' to detect hidden elements. – Ameen – 2013-12-05T04:57:08.733

@Kzqai Also, I believe this works: $(selector).is('not(:hidden)') – Izkata – 2014-02-03T22:43:52.150

This doesn't work in the latest jquery. It's been deprecated. What's the best work around? (Why did they remove this...?) – carl – 2014-02-11T06:46:25.643

@carl I don't see anything in the jQuery documentation about this being deprecated. I have also tested it with the latest jQuery and it does still work. Here: http://jsfiddle.net/F6atJ/

– BruceHill – 2014-06-24T15:51:18.307

This doesn't seem to return false if the element has opacity:0; set, any work around? – Keir Simmons – 2014-09-12T20:25:07.820

1Not working for element that have parent overflow: hidden; – Yana Agun Siswanto – 2015-02-04T08:03:57.983

135This solution would seem to encourage the confustion of visible=false and display:none; whereas Mote's solution clearly illistrates the coders intent to check the display:none; (via mention of hide and show which control display:none not visible=true) – kralco626 – 2010-12-29T18:30:57.670

78That is correct, but :visible will also check if the parent elements are visible, as chiborg pointed out. – Tsvetomir Tsonev – 2011-01-06T12:30:27.393

Tsvetomir, this doesn't work for IE7 - even when the elements are hidden it thinks that visible=true. Please correct your answer to avoid misleading people. visible and display are different properties and should be treated as such. Mote's answer is the correct one. – sarsnake – 2011-01-11T02:07:31.083

36

You have a point - I'll make it clear that the code checks only for the display property. Given that the the original question is for show() and hide(), and they set display, my answer is correct. By the way it does work with IE7, here's a test snippet - http://jsfiddle.net/MWZss/ ;

– Tsvetomir Tsonev – 2011-01-14T16:54:41.537

1Does not work on chrome though works flawlessly in firefox :( Had to do something like jQuery(textarea).parent().css('display') != 'none' instead of jQuery(textarea).parent().is(":visible") – Aniket Thakur – 2015-09-11T14:05:26.913

This doesn't work if it is hidden by a media query, how would I test for that? – SuperUberDuper – 2015-12-07T16:46:33.677

Changes in 1.12+ and 2.2.0+ and 3.0+ change the counts if multiple elements selected (see note at the bottom of this http://stackoverflow.com/a/17426800/125981)

– Mark Schultheiss – 2017-04-25T11:18:26.450

1 312

You can use the hidden selector:

// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')

twernt

Posted 2008-10-07T13:03:18.057

Reputation: 16 527

18On pages 21 to 28 it shows how slow :hidden or :visible is compared to other selectors. Thanks for pointing this. – Etienne Dupuis – 2012-07-04T20:12:04.820

90When you're dealing with a couple of elements and very little is going on - i.e. THE ABSURDLY VAST MAJORITY OF CASES - the time issue is a ridiculously minor concern. Oh, noes! It took 42 ms instead of 19 ms!!! – vbullinger – 2013-02-20T14:56:49.620

10I am toggling the element mamually using this selector. $('element:hidden') is always true for me! – ZoomIn – 2013-08-09T07:18:33.713

1

Could you explain why this one isn't working: http://jsfiddle.net/URHkb/ ?

– Wolfpack'08 – 2013-12-04T04:28:31.233

1:hidden is for form elements, not display:none. This is not the answer people are most likely expecting. – cwingrav – 2015-11-18T15:57:48.570

9@cwingrav You might want to re-read the documentation, :hidden applies to all elements. Form elements with type="hidden" is just one case that can trigger :hidden. Elements with no height and width, elements with display: none, and elements with hidden ancestors will also qualify as :hidden. – Joshua Walsh – 2016-01-15T04:15:16.690

3

The embedded presenation on the linked page no longer works, go to http://slideshare.net/AddyOsmani/jquery-proven-performance-tips-tricks/ instead.

– chiborg – 2016-02-23T14:59:46.737

4@vbullinger 42ms is actually a bit longer than I would like to wait for the website to respond to my actions - that means around 3 frames of animation dropped/delayed only at 60 fps – Sebi – 2016-07-30T09:13:45.787

2@vbullinger any processing that takes more than 16ms starts dropping FPS. So yes, if it takes 42ms it can be a bad deal if you're interested in performance. – Alejandro García Iglesias – 2017-08-02T14:45:06.900

54

just be careful, there are some good performance related tips in this presentation: http://addyosmani.com/jqprovenperformance/

– codecraig – 2011-07-11T17:05:57.480

1

From jQuery docs: "using :hidden heavily can have performance implications, as it may force the browser to re-render the page before it can determine visibility. Tracking the visibility of elements via other methods, using a class for example, can provide better performance."

– CPHPython – 2018-05-17T14:00:49.930

The link above to AddyOsmani's website is valid, but Slideshare no longer allows the flash embed. You can view the slides here https://www.slideshare.net/AddyOsmani/jquery-performance-tips-and-tricks-2011

– Craig London – 2018-11-14T16:13:04.060

826

if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
    // element is hidden
}

Above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").

For example,

<div id="div1" style="display:none">
  <div id="div2" style="display:block">Div2</div>
</div>

The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.

Mote

Posted 2008-10-07T13:03:18.057

Reputation: 8 495

12This is the only solution that worked for me when testing with IE 8. – evanmcd – 2012-01-13T18:51:41.507

120This only checks for the display property of a single element. The :visible attribute checks also the visibility of the parent elements. – chiborg – 2010-03-03T10:10:48.183

2This is not the solution to my problem but the method helped me identify a fix for checking against a property to my problem. – dchayka – 2014-03-14T17:37:17.573

14@chiborg Yes, but sometimes that's what you want and I had to learn the hard way how "clever" jQuery was... – Casey – 2014-03-14T17:56:14.667

7This does answer the question, being the question is about a single element and by using the hide(), show() and toggle() functions, however, as most have already said, we should use the :visible and :hidden pseudo-classes. – Jimmy Knoot – 2015-04-14T09:18:30.463

This answer can be used when an element exists but is not currently on the page, such as after detach(). – atheaos – 2017-04-25T16:05:39.277

471

None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):

$(".item").each(function() {
    if ($(this).css("visibility") == "hidden") {
        // handle non visible state
    } else {
        // handle visible state
    }
});

aaronLile

Posted 2008-10-07T13:03:18.057

Reputation: 4 747

15This answer is good to handle visibility literally, but the question was How you would test if an element has been hidden or shown using jQuery?. Using jQuery means: the display property. – MarioDS – 2013-05-11T22:37:45.240

8

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. See answer by Pedro Rainho and jQuery documentation on the :visible selector.

– awe – 2013-10-16T09:12:04.603

8you need to traverse up the DOM to check the node's parents, or else ,this is useless. – vsync – 2014-04-22T19:20:11.553

4this won't work if you hide element with .hide(). – user3197818 – 2015-08-06T05:51:23.840

340

From How do I determine the state of a toggled element?


You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.

var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');

If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:

 $('#myDiv:visible').animate({left: '+=200px'}, 'slow');

user574889

Posted 2008-10-07T13:03:18.057

Reputation: 3 409

2wondering why no answer mentions the case when element is moved away from the visible window, like top:-1000px... Guess it's an edge-case – jazzcat – 2017-05-08T09:34:11.833

251

Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.

So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.

So instead of an if statement, like this:

if ($('#btnUpdate').is(":visible"))
{
     $('#btnUpdate').animate({ width: "toggle" });   // Hide button
}

Or more efficient, but even uglier:

var button = $('#btnUpdate');
if (button.is(":visible"))
{
     button.animate({ width: "toggle" });   // Hide button
}

You can do it all in one line:

$('#btnUpdate').filter(":visible").animate({ width: "toggle" });

Simon_Weaver

Posted 2008-10-07T13:03:18.057

Reputation: 70 081

21No reason to extract the DOM node in the snippet used in the example, and then have to look it back up again. Better to just do: var $button = $('#btnUpdate');

And then in the If expressions just use $button instead of $(button). Has the advantage of caching the jQuery object. – LocalPCGuy – 2012-04-21T22:32:30.533

here's is a simple example http://www.jquerypot.com/how-to-check-an-element-is-visible-or-not-with-jquery/

– Ketan Savaliya – 2018-04-29T13:28:08.057

204

The :visible selector according to the jQuery documentation:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.

This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.

If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".

Also take into consideration the additional jQuery notes:

Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").

Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.

Pedro Rainho

Posted 2008-10-07T13:03:18.057

Reputation: 3 438

185

This works for me, and I am using show() and hide() to make my div hidden/visible:

if( $(this).css('display') == 'none' ){
    /* your code goes here */
} else {
    /* alternate logic   */
}

Abiy

Posted 2008-10-07T13:03:18.057

Reputation: 1 883

179

How element visibility and jQuery works;

An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:

  • 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 lets one to make an element partly transparent;

    if ($('.target').is(':hidden')) {
      $('.target').show();
    } else {
      $('.target').hide();
    }
    if ($('.target').is(':visible')) {
      $('.target').hide();
    } else {
      $('.target').show();
    }
    
    if ($('.target-visibility').css('visibility') == 'hidden') {
      $('.target-visibility').css({
        visibility: "visible",
        display: ""
      });
    } else {
      $('.target-visibility').css({
        visibility: "hidden",
        display: ""
      });
    }
    
    if ($('.target-visibility').css('opacity') == "0") {
      $('.target-visibility').css({
        opacity: "1",
        display: ""
      });
    } else {
      $('.target-visibility').css({
        opacity: "0",
        display: ""
      });
    }
    

    Useful jQuery toggle methods:

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

webvitaly

Posted 2008-10-07T13:03:18.057

Reputation: 2 774

19Another difference between visibility:hidden and opacity:0 is that the element will still respond to events (like clicks) with opacity:0. I learned that trick making a custom button for file uploads. – urraka – 2012-06-29T18:15:21.490

also if you hide input with opacity:0, it still gets selected with tab key – YangombiUmpakati – 2017-12-12T11:08:36.917

143

I would use CSS class .hide { display: none!important; }.

For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").

It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.

Evgeny Levin

Posted 2008-10-07T13:03:18.057

Reputation: 4 449

10.hasClass('hide') doesn't check if an ancestor of the parent is hidden (which would make it hidden too). You could possibly get this to work correctly by checking if .closest('.hide').length &gt; 0, but why reinvent the wheel? – nbrooks – 2012-09-25T23:57:15.207

Variant you propose returns if element visible on html, my variant returns if element was directly hidden by your javascript code/view engine. If your know that parent elements should never be hidden - use .hasClass() to be more strict and prevent future bugs. If you want to check not only visibility but element state set too - use .hasClass() too. In other cases .closest() is better. – Evgeny Levin – 2012-12-01T20:27:09.573

Why dont you just use .is(":visible")? – dont_trust_me – 2018-10-16T09:43:43.397

138

You can also do this using plain JavaScript:

function isRendered(domObj) {
    if ((domObj.nodeType != 1) || (domObj == document.body)) {
        return true;
    }
    if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
        return isRendered(domObj.parentNode);
    } else if (window.getComputedStyle) {
        var cs = document.defaultView.getComputedStyle(domObj, null);
        if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
            return isRendered(domObj.parentNode);
        }
    }
    return false;
}

Notes:

  1. Works everywhere

  2. Works for nested elements

  3. Works for CSS and inline styles

  4. Doesn't require a framework

Matt Brock

Posted 2008-10-07T13:03:18.057

Reputation: 4 502

5Works slightly differently to jQuery's; it considers visibility: hidden to be visible. – alex – 2012-09-20T04:45:23.303

3It's easy enough to change the code above to mimic the (arguably stupid) jQuery behavior. . . . . function isRendered(o){if((o.nodeType!=1)||(o==document.body)){return true;}if(o.currentStyle&&o.currentStyle["display"]!="none"){return isRendered(o.parentNode);}else if(window.getComputedStyle){if(document.defaultView.getComputedStyle(o, null).getPropertyValue("display")!="none"){return isRendered(o.parentNode);}}return false;} – Matt Brock – 2012-09-26T13:57:30.380

2Sure, I was just adding that for the benefit of users who used this without scanning its code. :) – alex – 2012-09-26T21:33:20.727

118

One can simply use the hidden or visible attribute, like:

$('element:hidden')
$('element:visible')

Or you can simplify the same with is as follows.

$(element).is(":visible")

ScoRpion

Posted 2008-10-07T13:03:18.057

Reputation: 7 118

108

Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).

think123

Posted 2008-10-07T13:03:18.057

Reputation: 10 356

103

$('#clickme').click(function() {
  $('#book').toggle('slow', function() {
    // Animation complete.
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
  Click here
</div>
<img id="book" src="http://www.chromefusion.com/wp-content/uploads/2012/06/chrome-logo.jpg" alt="" />

Source:

Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery

jsFiddle:

JSFiddle - ipsjolly - k4WWj

Code Spy

Posted 2008-10-07T13:03:18.057

Reputation: 3 070

@Adrew but this link is showing working example of this function. I think a practical answer may weight over a full page of text :) – Code Spy – 2013-01-25T06:30:44.343

@jolly.exe until that working example goes away that is. – Kevin B – 2013-10-10T21:49:17.457

100

ebdiv should be set to style="display:none;". It works for both show and hide:

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});

Vaishu

Posted 2008-10-07T13:03:18.057

Reputation: 1 637

84

When testing an element against :hidden selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.

This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:

Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]

So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.

Have a look at the following example:

console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
  position: absolute;
  left: 10px;
  top: 10px;
  background: #ff0000;
}

.bar {
  position: absolute;
  left: 10px;
  top: 10px;
  width: 20px;
  height: 20px;
  background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
  <div class="bar"></div>
</div>

UPDATE FOR JQUERY 3.x:

With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.

JSFiddle with jQuery 3.0.0-alpha1:

http://jsfiddle.net/pM2q3/7/

The same JS will then have this output:

console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false

conceptdeluxe

Posted 2008-10-07T13:03:18.057

Reputation: 2 696

80

This may work:

expect($("#message_div").css("display")).toBe("none");

Maneesh Kumar

Posted 2008-10-07T13:03:18.057

Reputation: 987

6What language/dialect/library is this? I'm not familiar with this syntax in JS... – nbrooks – 2012-09-25T23:31:33.623

It looks like a jasmine unit test.

– Mottie – 2017-03-23T00:48:31.640

60

Example:

$(document).ready(function() {
  if ($("#checkme:hidden").length) {
    console.log('Hidden');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
  <span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
  <br>Product: Salmon Atlantic
  <br>Specie: Salmo salar
  <br>Form: Steaks
</div>

Irfan DANISH

Posted 2008-10-07T13:03:18.057

Reputation: 4 807

59

To check if it is not visible I use !:

if ( !$('#book').is(':visible')) {
    alert('#book is not visible')
}

Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:

var $book = $('#book')

if(!$book.is(':visible')) {
    alert('#book is not visible')
}

Matthias Wegtun

Posted 2008-10-07T13:03:18.057

Reputation: 1 076

How did you determined that saving a selector in variable is really faster? – Ilia Rostovtsev – 2013-06-20T21:32:30.620

3

Hi @Ilia Rostovtsev http://jsperf.com/caching-jquery-selectors There you can run the test. Anyways it's nice to have it cached so it can be accessed faster

– Matthias Wegtun – 2013-06-21T06:56:50.137

2This is suitable if you want to use a single variable through out the process instead of calling and calling the same object. – Kenneth Palaganas – 2013-08-25T16:57:09.393

57

Use class toggling, not style editing . . .

Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.


JavaScript Best Practices and Optimization

Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:

Lopsided

Posted 2008-10-07T13:03:18.057

Reputation: 3 115

54

After all, none of examples suits me, so I wrote my own.

Tests (no support of Internet Explorer filter:alpha):

a) Check if the document is not hidden

b) Check if an element has zero width / height / opacity or display:none / visibility:hidden in inline styles

c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden / scroll / one element over enother) or screen edges

d) Check if an element has zero width / height / opacity or display:none / visibility:hidden in computed styles (among all ancestors)

Tested on

Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac Webkit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), Safari (Windows/Mac/iOS)

var is_visible = (function () {
    var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
        y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
        relative = !!((!x && !y) || !document.elementFromPoint(x, y));
        function inside(child, parent) {
            while(child){
                if (child === parent) return true;
                child = child.parentNode;
            }
        return false;
    };
    return function (elem) {
        if (
            document.hidden ||
            elem.offsetWidth==0 ||
            elem.offsetHeight==0 ||
            elem.style.visibility=='hidden' ||
            elem.style.display=='none' ||
            elem.style.opacity===0
        ) return false;
        var rect = elem.getBoundingClientRect();
        if (relative) {
            if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
        } else if (
            !inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
            (
                rect.top + elem.offsetHeight/2 < 0 ||
                rect.left + elem.offsetWidth/2 < 0 ||
                rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
                rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
            )
        ) return false;
        if (window.getComputedStyle || elem.currentStyle) {
            var el = elem,
                comp = null;
            while (el) {
                if (el === document) {break;} else if(!el.parentNode) return false;
                comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
                if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
                el = el.parentNode;
            }
        }
        return true;
    }
})();

How to use:

is_visible(elem) // boolean

Aleko

Posted 2008-10-07T13:03:18.057

Reputation: 835

54

Example of using the visible check for adblocker is activated:

$(document).ready(function(){
  if(!$("#ablockercheck").is(":visible"))
    $("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>

"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.

Roman Losev

Posted 2008-10-07T13:03:18.057

Reputation: 1 396

49

You need to check both... Display as well as visibility:

if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
    // The element is not visible
} else {
    // The element is visible
}

If we check for $(this).is(":visible"), jQuery checks for both the things automatically.

Premshankar Tiwari

Posted 2008-10-07T13:03:18.057

Reputation: 2 297

37

Maybe you can do something like this

$(document).ready(function() {
   var visible = $('#tElement').is(':visible');

   if(visible) {
      alert("visible");
                    // Code
   }
   else
   {
      alert("hidden");
   }
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<input type="text" id="tElement" style="display:block;">Firstname</input>

Mathias Stavrou

Posted 2008-10-07T13:03:18.057

Reputation: 640

31

Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout (as described for jQuery :visible Selector) - we can check if element is really visible in this way:

function isElementReallyHidden (el) {
    return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}

var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
    if (isElementReallyHidden(this)) {
        booElementReallyShowed = false;
    }
});

Andron

Posted 2008-10-07T13:03:18.057

Reputation: 4 639

29

if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}

Gaurav

Posted 2008-10-07T13:03:18.057

Reputation: 343

29

Simply check visibility by checking for a boolean value, like:

if (this.hidden === false) {
    // Your code
}

I used this code for each function. Otherwise you can use is(':visible') for checking the visibility of an element.

pixellabme

Posted 2008-10-07T13:03:18.057

Reputation: 407

29

But what if the element's CSS is like the following?

.element{
    position: absolute;left:-9999;    
}

So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.

RN Kushwaha

Posted 2008-10-07T13:03:18.057

Reputation: 1 439

28

A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}

Working Fiddle

V31

Posted 2008-10-07T13:03:18.057

Reputation: 6 922

27

Also here's a ternary conditional expression to check the state of the element and then to toggle it:

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });

cssimsek

Posted 2008-10-07T13:03:18.057

Reputation: 841

4Or, y'kno, just get rid of the entire conditional and say $('elementToToggle').toggle('slow');... :) – nbrooks – 2013-12-25T08:53:21.693

23

.is(":not(':hidden')") /*if shown*/

Kareem

Posted 2008-10-07T13:03:18.057

Reputation: 2 280

Because :not(':hidden') is not the same as is(':visible'). "Visible" works with css "opacity" not with JQuery "show()/hide()". Plus, there is no extra quotation. Every set plays a role in this little code. – Kareem – 2015-09-01T06:42:13.113

1) both :visible and :hidden check CSS element and ancestor visibility and not just the display: none as you now suggest. 2) quotes inside a pseudo-selector are not required if the selector contains only : and alphanumerics (e.g. :not(:hidden) is the same as not(':hidden') (only a little faster) and 3) how will you become better if you cannot accept that you may actually be incorrect sometimes? :) – Gone Coding – 2015-09-01T07:26:19.347

19

I searched for this, and none of the answers are correct for my case, so I've created a function that will return false if one's eyes can't see the element

jQuery.fn.extend({
  isvisible: function() {
    //
    //  This function call this: $("div").isvisible()
    //  Return true if the element is visible
    //  Return false if the element is not visible for our eyes
    //
    if ( $(this).css('display') == 'none' ){
        console.log("this = " + "display:none");
        return false;
    }
    else if( $(this).css('visibility') == 'hidden' ){
        console.log("this = " + "visibility:hidden");   
        return false;
    }
    else if( $(this).css('opacity') == '0' ){
        console.log("this = " + "opacity:0");
        return false;
    }   
    else{
        console.log("this = " + "Is Visible");
        return true;
    }
  }  
});

lmcDevloper

Posted 2008-10-07T13:03:18.057

Reputation: 307

17

if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}

Prabhagaran

Posted 2008-10-07T13:03:18.057

Reputation: 2 141

15

This is how jQuery internally solves this problem:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

If you don't use jQuery, you can just leverage this code and turn it into your own function:

function isVisible(elem) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

Which isVisible will return true as long as the element is visible.

Oriol

Posted 2008-10-07T13:03:18.057

Reputation: 3 672

14

There are quite a few ways to check if an element is visible or hidden in jQuery.

Demo HTML for example reference

<div id="content">Content</div>
<div id="content2" style="display:none">Content2</div>

Use Visibility Filter Selector $('element:hidden') or $('element:visible')

  • $('element:hidden'): Selects all elements that are hidden.

    Example:
       $('#content2:hidden').show();
    
  • $('element:visible'): Selects all elements that are visible.

    Example:
       $('#content:visible').css('color', '#EEE');
    

Read more at http://api.jquery.com/category/selectors/visibility-filter-selectors/

Use is() Filtering

    Example:
       $('#content').is(":visible").css('color', '#EEE');

    Or checking condition
    if ($('#content').is(":visible")) {
         // Perform action
    }

Read more at http://api.jquery.com/is/

Arun Karnawat

Posted 2008-10-07T13:03:18.057

Reputation: 410

12

You can use this:

$(element).is(':visible');

Example code

$(document).ready(function()
{
    $("#toggle").click(function()
    {
        $("#content").toggle();
    });

    $("#visiblity").click(function()
    {
       if( $('#content').is(':visible') )
       {
          alert("visible"); // Put your code for visibility
       }
       else
       {
          alert("hidden");
       }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

<p id="content">This is a Content</p>

<button id="toggle">Toggle Content Visibility</button>
<button id="visibility">Check Visibility</button>

Abrar Jahin

Posted 2008-10-07T13:03:18.057

Reputation: 6 093

12

As hide(), show() and toggle() attaches inline css (display:none or display:block) to element. Similarly, we can easily use ternary operator to check weather element is hidden or visible by checking display css.

UPDATE:

  • You also need to check if element css set to visibility: "visible" or visibility: "hidden"
  • Element will be also visible if display property set to inline-block, block, flex.

So we can check for property of element that makes it invisible. So they are display: none and visibility: "hidden";

We can create an object for checking property responsible for hiding element:

var hiddenCssProps = {
display: "none",
visibility: "hidden"
}

We can check by looping through each key value in object matching if element property for key matches with hidden property value.

var isHidden = false;
for(key in hiddenCssProps) {
  if($('#element').css(key) == hiddenCssProps[key]) {
     isHidden = true;
   }
}

If you want to check property like element height: 0 or width: 0 or more, you can extend this object and add more property to it and can check.

Thank you @Krzysztof Przygoda for reminding me other display properties.

No one

Posted 2008-10-07T13:03:18.057

Reputation: 788

12

Just simply check if that element is visible and it will return a boolean, jQuery hide the elements by adding display none to the element, so if you want to use pure JavaScript, you can still do that, for example:

if (document.getElementById("element").style.display === 'block') { 
  // your element is visible, do whatever you'd like
}

Also, you can use jQuery as seems the rest of your code using that and you have smaller block of code, something like below in jQuery, do the same track for you:

if ($(element).is(":visible")) { 
    // your element is visible, do whatever you'd like
};

Also using css method in jQuery can result the same thing:

if ($(element).css('display')==='block') {
    // your element is visible, do whatever you'd like
}

Also in case of checking for visibility and display, you can do the below:

if ($(this).css("display")==="block"||$(this).css("visibility")==="visible") {
   // your element is visible, do whatever you'd like
}

Alireza

Posted 2008-10-07T13:03:18.057

Reputation: 43 514

11

This is some option to check that tag is visible or not

 // using a pure CSS selector  
   if ($('p:visible')) {  
      alert('Paragraphs are visible (checked using a CSS selector) !');  
   };  
  
   // using jQuery's is() method  
   if ($('p').is(':visible')) {  
      alert('Paragraphs are visible (checked using is() method)!');  
   };  
  
   // using jQuery's filter() method  
   if ($('p').filter(':visible')) {  
      alert('Paragraphs are visible (checked using filter() method)!');  
   };  
  
   // you can use :hidden instead of :visible to reverse the logic and check if an element is hidden  
   // if ($('p:hidden')) {  
   //    do something  
   // };  

Sangeet Shah

Posted 2008-10-07T13:03:18.057

Reputation: 1 775

10

I just want to clarify that, in jQuery,

Elements can be considered hidden for several reasons:

  • They have a CSS display value of none.
  • They are form elements with type="hidden".
  • Their width and height are explicitly set to 0.
  • An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation.

Source: :hidden Selector | jQuery API Documentation

if($('.element').is(':hidden')) {
  // Do something
}

Sky Yip

Posted 2008-10-07T13:03:18.057

Reputation: 701

8

You can just add a class when it is visible. Add a class, show. Then check for it have a class:

$('#elementId').hasClass('show');

It returns true if you have the show class.

Add CSS like this:

.show{ display: block; }

Sahan

Posted 2008-10-07T13:03:18.057

Reputation: 312

7

There are too many methods to check for hidden elements. This is the best choice (I just recommended you):

Using jQuery, make an element, "display:none", in CSS for hidden.

The point is:

$('element:visible')

And an example for use:

$('element:visible').show();

Abdul Aziz Al Basyir

Posted 2008-10-07T13:03:18.057

Reputation: 588

4

You can use the

$( "div:visible" ).click(function() {
  $( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
  $( "div:hidden" ).show( "fast" );
});

API Documentation: https://api.jquery.com/visible-selector/

Wolfack

Posted 2008-10-07T13:03:18.057

Reputation: 960

4

Simply check for the display attribute (or visibility depending on what kind of invisibility you prefer). Example :

if ($('#invisible').css('display') == 'none') {
    // This means the HTML element with ID 'invisible' has its 'display' attribute set to 'none'
}

Antoine Auffray

Posted 2008-10-07T13:03:18.057

Reputation: 468

3

if($("h1").is(":hidden")){
    // your code..
}

cbertelegni

Posted 2008-10-07T13:03:18.057

Reputation: 335

2

1 • jQuery solution

Methods to determine if an element is visible in JQuery

<script>
if ($("#myelement").is(":visible")){alert ("#myelement is visible");}
if ($("#myelement").is(":hidden")){alert ("#myelement is hidden"); }
</script>

Loop on all visible div children of the element of id 'myelement' :

$("#myelement div:visible").each( function() {
 //Do something
});

Peeked at source of jQuery

This is how jQuery implements this feature :

jQuery.expr.filters.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

2 • How to check if an element is off-screen - CSS

Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):

jQuery.expr.filters.offscreen = function(el) {
  var rect = el.getBoundingClientRect();
  return (
           (rect.x + rect.width) < 0 
             || (rect.y + rect.height) < 0
             || (rect.x > window.innerWidth || rect.y > window.innerHeight)
         );
};

You could then use that in several ways:

// returns all elements that are offscreen
$(':offscreen');

// boolean returned if element is offscreen
$('div').is(':offscreen');

If you use Angular, check : Don’t use hidden attribute with Angular

Lyes CHIOUKH

Posted 2008-10-07T13:03:18.057

Reputation: 1 832

1

Some times, if you want to check if element is visible on page, depending on visibility of his parrent, you can check if width and height, of element, are equals to 0, both.

jQuery

$element.width() === 0 && $element.height() === 0

Vanilla

element.clientWidth === 0 && element.clientHeight === 0

Or

element.offsetWidth === 0 && element.offsetHeight === 0

Profesor08

Posted 2008-10-07T13:03:18.057

Reputation: 580

0

To be fair the question pre-dates this answer. I add it not to criticise the OP but to help anyone still asking this question.

The correct way to determine whether something is visible is to consult your view-model. If you don't know what that means then you are about to embark on a journey of discovery that will make your work a great deal less difficult.

Here's an overview of the model-view-viewmodel architecture (MVVM).

KnockoutJS is a binding library that will let you try this stuff out without learning an entire framework.

And here's some JS and a DIV that may or may not be visible.

<html><body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.1/knockout-min.js"></script>
<script>
var vm = {
  IsDivVisible: ko.observable(true);
}
vm.toggle = function(data, event) {
  //get current visibility state for the div
  var x = IsDivVisible();
  //set it to the opposite
  IsDivVisible(!x);
}
ko.applyBinding(vm);
</script>
<div data-bind="visible: IsDivVisible">Peekaboo!</div>
<button data-bind="click: toggle">Toggle the div's visibility</button>
</body></html>

Notice that the toggle function does not consult the DOM to determine the visibility of the div, it consults the view-model.

Peter Wone

Posted 2008-10-07T13:03:18.057

Reputation: 11 158

0

$('someElement').on('click', function(){ $('elementToToggle').is(':visible')

user6119825

Posted 2008-10-07T13:03:18.057

Reputation:

0

You can use a css class when it visible or hidden by toggling the class.

.show{ display :block; }

Set your jQuery toggleClass() or addClass() or removeClass();.

As an example,

jQuery('#myID').toggleClass('show')

The above code will add show css class when the element don't have show and will remove when it has show class.

And when you are checking if it visible or not, You can follow this jQuery code,

jQuery('#myID').hasClass('show');

Above code will return a boolean (true) when #myID element has our class (show) and false when it don't have the (show) class.

Sahan

Posted 2008-10-07T13:03:18.057

Reputation: 312

0

You can do this:

isHidden = function(element){
    return (element.style.display === "none");
};

if(isHidden($("element")) == true){
    // something
}

Judah rogan

Posted 2008-10-07T13:03:18.057

Reputation: 73

0

Instead of writing an event for every single element, Do this:

$('div').each(function(){
  if($(this).css('display') === 'none'){
    $(this).css({'display':'block'});
  }
});

Also you can use it on the inputs:

$('input').each(function(){
  if($(this).attr('type') === 'hidden'){
    $(this).attr('type', 'text');
  }
});

user10145552

Posted 2008-10-07T13:03:18.057

Reputation:

0

jQuery solution, quite old question but still I fell I can give a bit better answer for those who want to change the button text as well.

$(function(){
  $("#showHide").click(function(){
    var btn = $(this);
    $("#content").toggle(function () {
      btn.text($(this).css("display") === 'none' ? "Show" : "Hide");
    });
   });
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="showHide">Hide</button>
<div id="content">
  <h2>Some content</h2>
  <p>
  What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.
  </p>
</div>

Muhammad

Posted 2008-10-07T13:03:18.057

Reputation: 2 018