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

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



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


.hide()


.show()


.toggle()



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





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
Feb 1 '11 at 3:57



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





This is related although a different question: stackoverflow.com/questions/17425543/…
– Mark Schultheiss
Mar 22 '16 at 19:20





What is your definition of hidden?
– fabspro
May 19 at 7:29




51 Answers
51



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





This 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
Dec 29 '10 at 18:30



visible=false


display:none


display:none


display:none


visible=true





That is correct, but :visible will also check if the parent elements are visible, as chiborg pointed out.
– Tsvetomir Tsonev
Jan 6 '11 at 12:30


:visible





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 - jsfiddle.net/MWZss ;
– Tsvetomir Tsonev
Jan 14 '11 at 16:54



display


show()


hide()


display





I actually found that the reverse logic words better: !$('selector').is(':hidden'); for some reason. Worth a try.
– Kzqai
Jan 5 '12 at 15:36





Here's a simple benchmark testing is() against regexp: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
Jun 22 '12 at 14:12




You can use the hidden selector:


hidden


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



And the visible selector:


visible


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





just be careful, there are some good performance related tips in this presentation: addyosmani.com/jqprovenperformance
– codecraig
Jul 11 '11 at 17:05





On pages 21 to 28 it shows how slow :hidden or :visible is compared to other selectors. Thanks for pointing this.
– Etienne Dupuis
Jul 4 '12 at 20:12






When 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
Feb 20 '13 at 14:56





I am toggling the element mamually using this selector. $('element:hidden') is always true for me!
– ZoomIn
Aug 9 '13 at 7:18





@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
Jan 15 '16 at 4:15


type="hidden"


display: none


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").


.is(":hidden")


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


div2


:visible


:visible





This only checks for the display property of a single element. The :visible attribute checks also the visibility of the parent elements.
– chiborg
Mar 3 '10 at 10:10





This is the only solution that worked for me when testing with IE 8.
– evanmcd
Jan 13 '12 at 18:51





This is not the solution to my problem but the method helped me identify a fix for checking against a property to my problem.
– dchayka
Mar 14 '14 at 17:37





@chiborg Yes, but sometimes that's what you want and I had to learn the hard way how "clever" jQuery was...
– Casey
Mar 14 '14 at 17:56





This 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
Apr 14 '15 at 9:18



hide()


show()


toggle()


:visible


:hidden



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


visibility: hidden


:visible


:hidden


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

);





This 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
May 11 '13 at 22:37


visibility


How you would test if an element has been hidden or shown using jQuery?


display





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
Oct 16 '13 at 9:12



visibility: hidden


opacity: 0


:visible





you need to traverse up the DOM to check the node's parents, or else ,this is useless.
– vsync
Apr 22 '14 at 19:20






this won't work if you hide element with .hide().
– user3197818
Aug 6 '15 at 5:51



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.


:visible


:hidden


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:


:visible


:hidden


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





wondering 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
May 8 '17 at 9:34


top:-1000px



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.


filter(":visible")


filter(":hidden")



So instead of an if statement, like this:


if


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" );





No 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
Apr 21 '12 at 22:32






here's is a simple example jquerypot.com/…
– Ketan Savaliya
Apr 29 at 13:28



The :visible selector according to the jQuery documentation:


:visible


display


none


type="hidden"



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


visibility: hidden


opacity: 0



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.


display != none


.css("display") == 'none'



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


.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").


:visible


:visible


querySelectorAll()


:visible


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



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


show()


hide()


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



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


visibility:hidden


opacity:0


display:none


visibility:hidden



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;


opacity:0


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();
);





Another 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
Jun 29 '12 at 18:15


visibility:hidden


opacity:0


opacity:0





also if you hide input with opacity:0, it still gets selected with tab key
– YangombiUmpakati
Dec 12 '17 at 11:08



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


.hide display: none!important;



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


.addClass("hide")/.removeClass("hide")


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


.toggle()


.animate()





.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 > 0, but why reinvent the wheel?
– nbrooks
Sep 25 '12 at 23:57


.hasClass('hide')


.closest('.hide').length > 0





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
Dec 1 '12 at 20:27




You can also do this using plain JavaScript:


function isRendered(domObj)



Notes:



Works everywhere



Works for nested elements



Works for CSS and inline styles



Doesn't require a framework





Works slightly differently to jQuery's; it considers visibility: hidden to be visible.
– alex
Sep 20 '12 at 4:45


visibility: hidden





It's easy enough to change the code above to mimic the (arguably stupid) jQuery behavior. . . . . function isRendered(o)
– Matt Brock
Sep 26 '12 at 13:57






Sure, I was just adding that for the benefit of users who used this without scanning its code. :)
– alex
Sep 26 '12 at 21:33



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


hidden


visible


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



Or you can simplify the same with is as follows.


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



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


if (!$('#thetagname').length)




$('#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





@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
Jan 25 '13 at 6:30





@jolly.exe until that working example goes away that is.
– Kevin B
Oct 10 '13 at 21:49



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


ebdiv


style="display:none;"


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



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.


:hidden



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



This may work:


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





What language/dialect/library is this? I'm not familiar with this syntax in JS...
– nbrooks
Sep 25 '12 at 23:31





It looks like a jasmine unit test.
– Mottie
Mar 23 '17 at 0:48



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





How did you determined that saving a selector in variable is really faster?
– Ilia Rostovtsev
Jun 20 '13 at 21:32





Hi @Ilia Rostovtsev 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
Jun 21 '13 at 6:56





This is suitable if you want to use a single variable through out the process instead of calling and calling the same object.
– Kenneth Palaganas
Aug 25 '13 at 16:57



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>



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.


Display



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



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.



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



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


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


display:none


visibility:hidden



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


overflow:hidden



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


display:none



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 () )();



How to use:


is_visible(elem) // boolean



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.


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



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>



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:


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


function isElementReallyHidden (el) $(el).css('opacity') == 0;


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

);


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



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.



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



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.


is(':visible')



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'); );





Or, y'kno, just get rid of the entire conditional and say $('elementToToggle').toggle('slow');... :)
– nbrooks
Dec 25 '13 at 8:53


$('elementToToggle').toggle('slow');


:)




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

ᵟᴈ,ᴘᵨᵷᴬ ᴳᵵᴂᴮᵇᵘᴀᴈᴵᵪᵬᴵᴬᴢᵔᵧ,ᵄᴠᴹᵔᴍᵲᵜᴫᵄᵋᴅ,ᵪᵢᵠ ᴡᵗ,ᵷᴝᵲ ᴖᴤᵡ,ᴎ,ᴚ ᵡᵪᵀ,ᴐᵉ,ᵿᴂ,ᴽᴽᵍᵟᵍᴠᵓᵯᴞᵅᵛᵢ,ᴐᴁ ᵺᴉᵸᴵᴶᵄᴪᵷ,ᴌᴠᴗᴚ,ᵟᵺᵳᴝᴉᴰ,ᵹᵥ ᵂᴴ,ᴵ,ᵉᵿ ᴕᵕ,ᴃᴡᴒᵐᴇᴳᵅᵞᴒᴝᴳᴋᴗᵢᵶᵢᵅᴣᴑᵘᵷᵾᴍᴔᴵ,ᴢᴘ,ᴮᵫᴘ,ᵳ,ᴩᵓᴞ