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

Is it 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?

This question is related to javascript jquery dom visibility

The answer is


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


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

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

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

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

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


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


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

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

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
}

if($(element).is(":visible")) {
  console.log('element is visible');
} else {
  console.log('element is not visible');
}

Example:

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


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

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.


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

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


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

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.


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


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

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

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

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.


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

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

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.


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:


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

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


A jQuery solution, but it is still a bit better for those who want to change the button text as well:

_x000D_
_x000D_
$(function(){_x000D_
  $("#showHide").click(function(){_x000D_
    var btn = $(this);_x000D_
    $("#content").toggle(function () {_x000D_
      btn.text($(this).css("display") === 'none' ? "Show" : "Hide");_x000D_
    });_x000D_
   });_x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button id="showHide">Hide</button>_x000D_
<div id="content">_x000D_
  <h2>Some content</h2>_x000D_
  <p>_x000D_
  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._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


You can also:

   hideShow(){
  $("#accordionZiarat").hide();
  // Checks CSS content for display:[none|block], ignores visibility:[true|false]
  if ($("#accordionZiarat").is(":visible")) {
    $("#accordionZiarat").hide();
  }

  
  else if ($("#accordionZiarat").is(":hidden")) {
    $("#accordionZiarat").show();
  }

  else{

  }

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

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

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

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

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

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

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


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

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


You can use the

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

API Documentation: visible Selector


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/


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

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


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>

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:

_x000D_
_x000D_
console.log($('.foo').is(':hidden')); // true_x000D_
console.log($('.bar').is(':hidden')); // false
_x000D_
.foo {_x000D_
  position: absolute;_x000D_
  left: 10px;_x000D_
  top: 10px;_x000D_
  background: #ff0000;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  position: absolute;_x000D_
  left: 10px;_x000D_
  top: 10px;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background: #0000ff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo">_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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 JavaScript code will then have this output:

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

Demo Link

_x000D_
_x000D_
$('#clickme').click(function() {_x000D_
  $('#book').toggle('slow', function() {_x000D_
    // Animation complete._x000D_
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="clickme">_x000D_
  Click here_x000D_
</div>_x000D_
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
_x000D_
_x000D_
_x000D_

Source:

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


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>

This may work:

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

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.


Using hidden selection you can match all hidden elements

$('element:hidden')

Using Visible selection you can match all visible elements

$('element:visible')

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


if($(element).is(":visible")) {
  console.log('element is visible');
} else {
  console.log('element is not visible');
}

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

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


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

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

Example of using the visible check for adblocker is activated:

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

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


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

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

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

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

// You can also do this...

        $("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.");
                }
            });
        });

Try

content.style.display != 'none'

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


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.


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.


Demo Link

_x000D_
_x000D_
$('#clickme').click(function() {_x000D_
  $('#book').toggle('slow', function() {_x000D_
    // Animation complete._x000D_
    alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="clickme">_x000D_
  Click here_x000D_
</div>_x000D_
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
_x000D_
_x000D_
_x000D_

Source:

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


Example:

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


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

This may work:

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

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


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.


You can do this:

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

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

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

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

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.


A jQuery solution, but it is still a bit better for those who want to change the button text as well:

_x000D_
_x000D_
$(function(){_x000D_
  $("#showHide").click(function(){_x000D_
    var btn = $(this);_x000D_
    $("#content").toggle(function () {_x000D_
      btn.text($(this).css("display") === 'none' ? "Show" : "Hide");_x000D_
    });_x000D_
   });_x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button id="showHide">Hide</button>_x000D_
<div id="content">_x000D_
  <h2>Some content</h2>_x000D_
  <p>_x000D_
  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._x000D_
  </p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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.


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

You can use this:

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

Example code

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("#toggle").click(function()_x000D_
    {_x000D_
        $("#content").toggle();_x000D_
    });_x000D_
_x000D_
    $("#visiblity").click(function()_x000D_
    {_x000D_
       if( $('#content').is(':visible') )_x000D_
       {_x000D_
          alert("visible"); // Put your code for visibility_x000D_
       }_x000D_
       else_x000D_
       {_x000D_
          alert("hidden");_x000D_
       }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>_x000D_
_x000D_
<p id="content">This is a Content</p>_x000D_
_x000D_
<button id="toggle">Toggle Content Visibility</button>_x000D_
<button id="visibility">Check Visibility</button>
_x000D_
_x000D_
_x000D_


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.


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

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

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

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.


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
}

Maybe you can do something like this

_x000D_
_x000D_
$(document).ready(function() {_x000D_
   var visible = $('#tElement').is(':visible');_x000D_
_x000D_
   if(visible) {_x000D_
      alert("visible");_x000D_
                    // Code_x000D_
   }_x000D_
   else_x000D_
   {_x000D_
      alert("hidden");_x000D_
   }_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<input type="text" id="tElement" style="display:block;">Firstname</input>
_x000D_
_x000D_
_x000D_


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

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

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


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

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


You can use the

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

API Documentation: visible Selector


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

// You can also do this...

        $("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.");
                }
            });
        });

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.


Using hidden selection you can match all hidden elements

$('element:hidden')

Using Visible selection you can match all visible elements

$('element:visible')

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

You can do this:

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

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

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

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/


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:

_x000D_
_x000D_
console.log($('.foo').is(':hidden')); // true_x000D_
console.log($('.bar').is(':hidden')); // false
_x000D_
.foo {_x000D_
  position: absolute;_x000D_
  left: 10px;_x000D_
  top: 10px;_x000D_
  background: #ff0000;_x000D_
}_x000D_
_x000D_
.bar {_x000D_
  position: absolute;_x000D_
  left: 10px;_x000D_
  top: 10px;_x000D_
  width: 20px;_x000D_
  height: 20px;_x000D_
  background: #0000ff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo">_x000D_
  <div class="bar"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


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 JavaScript code will then have this output:

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

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

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 another) 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), and 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

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

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

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

Example of using the visible check for adblocker is activated:

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

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


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.


Maybe you can do something like this

_x000D_
_x000D_
$(document).ready(function() {_x000D_
   var visible = $('#tElement').is(':visible');_x000D_
_x000D_
   if(visible) {_x000D_
      alert("visible");_x000D_
                    // Code_x000D_
   }_x000D_
   else_x000D_
   {_x000D_
      alert("hidden");_x000D_
   }_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<input type="text" id="tElement" style="display:block;">Firstname</input>
_x000D_
_x000D_
_x000D_


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

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


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 another) 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), and 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

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

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.


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

You can use this:

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

Example code

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("#toggle").click(function()_x000D_
    {_x000D_
        $("#content").toggle();_x000D_
    });_x000D_
_x000D_
    $("#visiblity").click(function()_x000D_
    {_x000D_
       if( $('#content').is(':visible') )_x000D_
       {_x000D_
          alert("visible"); // Put your code for visibility_x000D_
       }_x000D_
       else_x000D_
       {_x000D_
          alert("hidden");_x000D_
       }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>_x000D_
_x000D_
<p id="content">This is a Content</p>_x000D_
_x000D_
<button id="toggle">Toggle Content Visibility</button>_x000D_
<button id="visibility">Check Visibility</button>
_x000D_
_x000D_
_x000D_


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

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

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.


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

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

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.


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

You can also:

   hideShow(){
  $("#accordionZiarat").hide();
  // Checks CSS content for display:[none|block], ignores visibility:[true|false]
  if ($("#accordionZiarat").is(":visible")) {
    $("#accordionZiarat").hide();
  }

  
  else if ($("#accordionZiarat").is(":hidden")) {
    $("#accordionZiarat").show();
  }

  else{

  }

Try

content.style.display != 'none'

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


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


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
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to visibility

document.getElementById("remember").visibility = "hidden"; not working on a checkbox Calling the base class constructor from the derived class constructor Equivalent of jQuery .hide() to set visibility: hidden Making a button invisible by clicking another button in HTML Why is visible="false" not working for a plain html table? Make one div visible and another invisible Animate visibility modes, GONE and VISIBLE How to change visibility of layout programmatically How can I make visible an invisible control with jquery? (hide and show not work) How to check visibility of software keyboard in Android?