8740

How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?

How do I test if an element is visible or hidden?

3

67 Answers 67

32
.is(":not(':hidden')") /*if shown*/ 
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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? :)
24
if($('#id_element').is(":visible")){ alert('shown'); }else{ alert('hidden'); } 

Comments

21

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

2 Comments

Just a note, if the selector returns an empty set of items, this method will return true, so check length first if you looking for invisible items : var items = jQuery('.selector'); if (items.length == 0 || !items.isVisible()) { alert('item is not visible'); }
What about elements which are hidden beneath other items?
21

As hide(), show() and toggle() attaches inline css (display:none or display:block) to element. Similarly, we can easily use the ternary operator to check whether the 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"
  • The element will be also visible if display property set to inline-block, block, flex.

So we can check for the property of an 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.

Comments

20

Just simply check if that element is visible and it will return a boolean. jQuery hides 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 it seems the rest of your code is using that and you have smaller block of code. Something like the below in jQuery does the same trick for you:

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

Also using the css method in jQuery can result in 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 } 

Comments

18

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/

Comments

17

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.

Comments

17

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>

Comments

15

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 } 

Comments

14

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

Comments

12

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 // }; 

Comments

12

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

Comments

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

API Documentation: visible Selector

Comments

9

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

Comments

9

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

Comments

8

Use any of visible Selector or hidden Selector to check visiblity:

  1. Use :visible Selector - jQuery( ":visible" )
  2. Use :hidden Selector - jQuery( ":hidden" )

use .toggle() - Display and hide element

function checkVisibility() { // check if element is hidden or not and return true false console.log($('#element').is(':hidden')); // check if element is visible or not and return true false console.log($('#element').is(':visible')); if ( $('#element').css('display') == 'none' || $('#element').css("visibility") == "hidden"){ console.log('element is hidden'); } else { console.log('element is visibile'); } } checkVisibility() $('#toggle').click(function() { $('#element').toggle() checkVisibility() })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id='toggle'>Toggle</button> <div style='display:none' id='element'> <h1>Hello</h1> <p>it's visible</p> </div>

Comments

7

Using hidden selection you can match all hidden elements

$('element:hidden') 

Using Visible selection you can match all visible elements

$('element:visible') 

Comments

7

There are two ways to check visibility of element.

Solution #1

if($('.selector').is(':visible')){ // element is visible }else{ // element is hidden } 

Solution #2

if($('.selector:visible')){ // element is visible }else{ // element is hidden } 

Comments

6

If you want to check if an element is visible on the page, depending on the visibility of its parent, you can check if width and height of the element are both equal to 0.

jQuery

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

Vanilla

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

Or

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

Comments

6

A jQuery solution, but it is still a bit better 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>

Comments

6

Extended function for checking if element is visible, display none, or even the opacity level

It returns false if the element is not visible.

function checkVisible(e) { if (!(e instanceof Element)) throw Error('not an Element'); const elementStyle = getComputedStyle(e); if (elementStyle.display === 'none' || elementStyle.visibility !== 'visible' || elementStyle.opacity < 0.1) return false; if (e.offsetWidth + e.offsetHeight + e.getBoundingClientRect().height + e.getBoundingClientRect().width === 0) { return false; } const elemCenter = { x: e.getBoundingClientRect().left + e.offsetWidth / 2, y: e.getBoundingClientRect().top + e.offsetHeight / 2 }; if (elemCenter.x < 0 || elemCenter.y < 0) return false; if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false; if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false; let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y); do { if (pointContainer === e) return true; } while (pointContainer = pointContainer.parentNode); return false; } 

Comments

5

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-view-model architecture (MVVM).

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

And here's some JavaScript code 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.

Comments

5
isHidden = function(element){ return (element.style.display === "none"); }; if(isHidden($("element")) == true){ // Something } 

Comments

4

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.

Comments

4

The below code checks if an element is hidden in jQuery or visible:

$("button").click(function () { // show hide paragraph on button click $("p").toggle("slow", function () { // check paragraph once toggle effect is completed if ($("p").is(":visible")) { alert("The paragraph is visible."); } else { alert("The paragraph is hidden."); } }); }); 

Comments

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

Comments

3

You can use jQuery's is() function to check the selected element visible or hidden. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match otherwise returns false.

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

Comments

3
content.style.display != 'none' 

function toggle() { $(content).toggle(); let visible= content.style.display != 'none' console.log('visible:', visible); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button onclick="toggle()">Show/hide</button> <div id="content">ABC</div>

Comments

3

You can try this:

$(document).ready(function () { var view = $(this).is(":visible"); if (view) { alert("view"); // Code } else { alert("hidden"); } }); 

1 Comment

if(content.not(":visible").length){
3
// One element let isVisible = $("#myButton")[0].checkVisibility(); // Returns true or false 
// Multiple elements $("div").each((i, el) => if (el.checkVisibility()) { /* el is visible... */ }); 

The new Element.checkVisibility() checks a variety of factors for visibility, including display:none, visibility, content-visibility, and opacity. You can specify those options:

let isVisible = $("#myButton")[0].checkVisibility({ opacityProperty: true, // Check CSS opacity property too visibilityProperty: true // Check CSS visibility property too }); 

See the answer for plain/vanilla JavaScript for more information.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.