8613

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?

Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135
Philip Morton
  • 129,733
  • 38
  • 88
  • 97
  • 67
    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](http://en.wikipedia.org/wiki/Internet_Explorer_8). This can be tested using [Tsvetomir Tsonev's helpful test snippet](http://stackoverflow.com/questions/178325/testing-if-something-is-hidden-with-jquery/178450#178450). Just remember to change the version of jQuery, to test under each one. – Reuben Feb 01 '11 at 03:57
  • 4
    This is related although a different question: http://stackoverflow.com/questions/17425543/difference-between-hidden-and-notvisible-in-jquery/17426800#17426800 – Mark Schultheiss Mar 22 '16 at 19:20
  • 1
    If you are not interested in virtual css element hiding, but physical visibility in "viewport area" for user then cosider to see https://stackoverflow.com/questions/487073/how-to-check-if-element-is-visible-after-scrolling and https://stackoverflow.com/questions/123999/how-can-i-tell-if-a-dom-element-is-visible-in-the-current-viewport – user1742529 Jan 02 '21 at 13:16

65 Answers65

10209

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

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

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

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

We use jQuery's is() to check the selected element with another element, selector or any jQuery object. 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 return false.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Tsvetomir Tsonev
  • 105,726
  • 5
  • 27
  • 34
  • 182
    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
  • 100
    That is correct, but `:visible` will also check if the parent elements are visible, as chiborg pointed out. – Tsvetomir Tsonev Jan 06 '11 at 12:30
  • 2
    Tsvetomir, this doesn't work for IE7 - even when the elements are hidden it thinks that visible=true. Please correct your answer to avoid misleading people. visible and display are different properties and should be treated as such. Mote's answer is the correct one. – sarsnake Jan 11 '11 at 02:07
  • 51
    You have a point - I'll make it clear that the code checks only for the `display` property. Given that the the original question is for `show()` and `hide()`, and they set `display`, my answer is correct. By the way it does work with IE7, here's a test snippet - http://jsfiddle.net/MWZss/ ; – Tsvetomir Tsonev Jan 14 '11 at 16:54
  • 60
    I actually found that the reverse logic words better: !$('selector').is(':hidden'); for some reason. Worth a try. – Kzqai Jan 05 '12 at 15:36
  • 24
    Here's a simple benchmark testing is() against regexp:http://jsperf.com/jquery-is-vs-regexp-for-css-visibility. Conclusion: if you're out for performance, use regexp over is() (since is() looks for all hidden nodes first before looking at the actual element). – Max Leske Jun 22 '12 at 14:12
  • 4
    Tchalvak, you may feel something is right, but try to explain why. Double negation is confusing as opposed to simple statement, so $('selector').is(':shown'); is much clearer than !$('selector').is(':hidden'); – Yasen Sep 10 '12 at 09:43
  • 3
    @TsvetomirTsonev, to check the parent's visibility, you can use $(element).parent().is(":visible"); I know this is bit old, but will useful for new search – Robin Michael Poothurai Oct 23 '12 at 08:43
  • 3
    What does `$(element).is(":visible")` return, if the element is visible in terms of not `having display:none` or `visibility:hidden`, but the user scrolled down so he doesn't actually see it? Is there a simple way to check that? – Martin Thoma Jan 02 '13 at 21:30
  • 2
    For other users wondering if this really does work in IE7, this might save you some time - it works, jquery 1.9.1: http://imgur.com/uKD4t8h – Chris Moschini Mar 27 '13 at 23:02
  • 2
    @MaxLeske - I'm pretty sure it's a GIVEN! (most of the time) that when you pull out the regexp knife that you'll take a perf. hit. The extra checks will be nil compared to the overhead/processing of regexp. – Bill Ortell Apr 17 '13 at 13:51
  • 2
    How do you do the inverse of this? – Robert Johnstone Aug 30 '13 at 11:46
  • 3
    I [found this informative](http://blog.jquery.com/2009/02/20/jquery-1-3-2-released/#:visible.2F:hidden_Overhauled) when looking up about `:visible` and `:hidden`. Essentially, it looks at the `offsetHeight` and `offsetWidth` allowing it to provide the best coverage (eg. you might have a class which has `display:none;` as a property and it will correctly report whether it is visible) – Turnerj Oct 17 '13 at 01:53
  • 2
    So, should we use `.is(":invisible")` for false? Or `!$(element).is(":visible")`, or just what? – Wolfpack'08 Dec 04 '13 at 01:58
  • 2
    @Wolfpack'08: I'm looking for a similar solution as well. So far I've been using `$(element).css('display')=='none'` to detect hidden elements. – Ameen Dec 05 '13 at 04:57
  • 2
    @Kzqai Also, I believe this works: `$(selector).is('not(:hidden)')` – Izkata Feb 03 '14 at 22:43
  • 1
    This doesn't work in the latest jquery. It's been deprecated. What's the best work around? (Why did they remove this...?) – carl Feb 11 '14 at 06:46
  • 1
    @carl I don't see anything in the jQuery documentation about this being deprecated. I have also tested it with the latest jQuery and it does still work. Here: http://jsfiddle.net/F6atJ/ – BruceHill Jun 24 '14 at 15:51
  • 2
    Not working for element that have parent `overflow: hidden;` – Yana Agun Siswanto Feb 04 '15 at 08:03
  • 2
    Does not work on chrome though works flawlessly in firefox :( Had to do something like `jQuery(textarea).parent().css('display') != 'none'` instead of `jQuery(textarea).parent().is(":visible")` – Aniket Thakur Sep 11 '15 at 14:05
  • 1
    Changes in 1.12+ and 2.2.0+ and 3.0+ change the counts if multiple elements selected (see note at the bottom of this http://stackoverflow.com/a/17426800/125981) – Mark Schultheiss Apr 25 '17 at 11:18
  • 1
    Does not work with jQuery UI Selectmenu, It says my option is hidden even though it is visible. – Black May 20 '19 at 14:20
  • In the off chance it helps anyone: If you're using an animation, such as `toggle("slow")`, you need to use the callback option and check the visibility there. – Broots Waymb Mar 02 '20 at 15:20
1612

You can use the hidden selector:

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

And the visible selector:

// Matches all elements that are visible
$('element:visible')
twernt
  • 20,271
  • 5
  • 32
  • 41
  • 71
    just be careful, there are some good performance related tips in this presentation: http://addyosmani.com/jqprovenperformance/ – codecraig Jul 11 '11 at 17:05
  • 29
    On pages 21 to 28 it shows how slow :hidden or :visible is compared to other selectors. Thanks for pointing this. – Etienne Dupuis Jul 04 '12 at 20:12
  • 116
    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
  • 18
    I am toggling the element mamually using this selector. $('element:hidden') is always true for me! – ZoomIn Aug 09 '13 at 07:18
  • 2
    :hidden is for form elements, not display:none. This is not the answer people are most likely expecting. – cwingrav Nov 18 '15 at 15:57
  • 16
    @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 04:15
  • 4
    The embedded presenation on the linked page no longer works, go to http://slideshare.net/AddyOsmani/jquery-proven-performance-tips-tricks/ instead. – chiborg Feb 23 '16 at 14:59
  • 6
    @vbullinger 42ms is actually a bit longer than I would like to wait for the website to respond to my actions - that means around 3 frames of animation dropped/delayed only at 60 fps – Sebi Jul 30 '16 at 09:13
  • 4
    @vbullinger any processing that takes more than 16ms starts dropping FPS. So yes, if it takes 42ms it can be a bad deal if you're interested in performance. – Alejandro García Iglesias Aug 02 '17 at 14:45
  • 3
    From [jQuery docs](https://api.jquery.com/hidden-selector): "using `:hidden` heavily can have performance implications, as it **may force the browser to re-render the page before it can determine visibility**. Tracking the visibility of elements via other methods, using a class for example, can provide better performance." – CPHPython May 17 '18 at 14:00
  • 3
    The link above to AddyOsmani's website is valid, but Slideshare no longer allows the flash embed. You can view the slides here https://www.slideshare.net/AddyOsmani/jquery-performance-tips-and-tricks-2011 – Craig London Nov 14 '18 at 16:13
1089
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mote
  • 11,197
  • 1
  • 18
  • 10
  • 138
    This only checks for the display property of a single element. The :visible attribute checks also the visibility of the parent elements. – chiborg Mar 03 '10 at 10:10
  • 17
    This is the only solution that worked for me when testing with IE 8. – evanmcd Jan 13 '12 at 18:51
  • 21
    @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
  • 9
    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 09:18
  • 2
    This answer can be used when an element exists but is not currently on the page, such as after detach(). – atheaos Apr 25 '17 at 16:05
588

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
    }
});
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
aaronLile
  • 5,917
  • 1
  • 14
  • 3
  • 23
    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
  • 13
    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**](http://stackoverflow.com/a/8266879/109392) and [jQuery documentation](http://api.jquery.com/visible-selector) on the `:visible` selector. – awe Oct 16 '13 at 09:12
  • 10
    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
431

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');
Chris
  • 135
  • 2
  • 7
user574889
  • 4,319
  • 1
  • 14
  • 2
  • 6
    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 08 '17 at 09:34
328

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

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" });
user16217248
  • 3,119
  • 19
  • 19
  • 37
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689
  • 25
    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
  • 2
    here's is a simple example http://www.jquerypot.com/how-to-check-an-element-is-visible-or-not-with-jquery/ – Ketan Savaliya Apr 29 '18 at 13:28
270

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.

Pang
  • 9,564
  • 146
  • 81
  • 122
Pedro Rainho
  • 4,234
  • 1
  • 19
  • 21
240

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();
    });
    
Eugen
  • 537
  • 6
  • 14
webvitaly
  • 4,241
  • 8
  • 30
  • 48
  • 22
    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
  • 3
    also if you hide input with opacity:0, it still gets selected with tab key – YangombiUmpakati Dec 12 '17 at 11:08
236

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   */
}
webvitaly
  • 4,241
  • 8
  • 30
  • 48
Abiy
  • 2,393
  • 1
  • 13
  • 2
183

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

Lucas
  • 16,930
  • 31
  • 110
  • 182
Matt Brock
  • 5,337
  • 1
  • 27
  • 26
  • 7
    Works slightly differently to jQuery's; it considers `visibility: hidden` to be *visible*. – alex Sep 20 '12 at 04:45
  • 5
    It's easy enough to change the code above to mimic the (arguably stupid) jQuery behavior. . . . . function isRendered(o){if((o.nodeType!=1)||(o==document.body)){return true;}if(o.currentStyle&&o.currentStyle["display"]!="none"){return isRendered(o.parentNode);}else if(window.getComputedStyle){if(document.defaultView.getComputedStyle(o, null).getPropertyValue("display")!="none"){return isRendered(o.parentNode);}}return false;} – Matt Brock Sep 26 '12 at 13:57
179

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.

Lucas
  • 16,930
  • 31
  • 110
  • 182
David Levin
  • 6,573
  • 5
  • 48
  • 80
  • 13
    `.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
  • 2
    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. – David Levin Dec 01 '12 at 20:27
157

Demo Link

$('#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="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>

Source (from my blog):

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

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Code Spy
  • 9,626
  • 4
  • 66
  • 46
147

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

$(document).ready(function(){
    $("#eb").click(function(){
        $("#ebdiv").toggle();
    });    
});
Community
  • 1
  • 1
Vaishu
  • 2,333
  • 3
  • 23
  • 25
145

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")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ScoRpion
  • 11,364
  • 24
  • 66
  • 89
133

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

Lucas
  • 16,930
  • 31
  • 110
  • 182
116

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

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

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

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

Have a look at the following example:

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

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

Update for jQuery 3.x:

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

JSFiddle with jQuery 3.0.0-alpha1:

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

The same JavaScript code will then have this output:

console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
conceptdeluxe
  • 3,753
  • 3
  • 25
  • 29
105
expect($("#message_div").css("display")).toBe("none");
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Maneesh Kumar
  • 1,367
  • 2
  • 9
  • 13
88

$(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>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Irfan DANISH
  • 8,349
  • 12
  • 42
  • 67
70

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')
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matthias Wegtun
  • 1,231
  • 1
  • 9
  • 13
  • 2
    How did you determined that saving a selector in variable is really faster? – Ilia Ross Jun 20 '13 at 21:32
  • 4
    Hi @Ilia Rostovtsev http://jsperf.com/caching-jquery-selectors There you can run the test. Anyways it's nice to have it cached so it can be accessed faster – Matthias Wegtun Jun 21 '13 at 06:56
  • 3
    This is suitable if you want to use a single variable through out the process instead of calling and calling the same object. – Kenneth P. Aug 25 '13 at 16:57
65

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:

Community
  • 1
  • 1
Ross Brasseaux
  • 3,879
  • 1
  • 28
  • 48
65

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aleko
  • 960
  • 1
  • 9
  • 10
63

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.

Cameron
  • 27,963
  • 100
  • 281
  • 483
Roman Losev
  • 1,911
  • 19
  • 26
56

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

var $this = $(this)
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.

user16217248
  • 3,119
  • 19
  • 19
  • 37
Premshankar Tiwari
  • 3,006
  • 3
  • 24
  • 30
56

$(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>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Mathias Stavrou
  • 871
  • 1
  • 8
  • 16
43

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.

dippas
  • 58,591
  • 15
  • 114
  • 126
pixellabme
  • 545
  • 4
  • 4
40

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

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

var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
    if (isElementReallyHidden(this)) {
        booElementReallyShowed = false;
    }
});
Andron
  • 6,413
  • 4
  • 43
  • 56
38

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.

Community
  • 1
  • 1
RN Kushwaha
  • 2,081
  • 3
  • 29
  • 40
36

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
V31
  • 7,626
  • 3
  • 26
  • 44
35

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

$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
cssimsek
  • 1,255
  • 14
  • 20
  • 4
    Or, y'kno, just get rid of the entire conditional and say `$('elementToToggle').toggle('slow');`... `:)` – nbrooks Dec 25 '13 at 08:53
34
if($('#postcode_div').is(':visible')) {
    if($('#postcode_text').val()=='') {
        $('#spanPost').text('\u00a0');
    } else {
        $('#spanPost').text($('#postcode_text').val());
}
dcodesmith
  • 9,590
  • 4
  • 36
  • 40
Gaurav
  • 413
  • 5
  • 9
31
.is(":not(':hidden')") /*if shown*/
Kareem
  • 5,068
  • 44
  • 38
  • 1
    Because :not(':hidden') is not the same as is(':visible'). "Visible" works with css "opacity" not with JQuery "show()/hide()". Plus, there is no extra quotation. Every set plays a role in this little code. – Kareem Sep 01 '15 at 06:42
  • 1
    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? :) – iCollect.it Ltd Sep 01 '15 at 07:26
23
if($('#id_element').is(":visible")){
   alert('shown');
}else{
   alert('hidden');
}
Prabhagaran
  • 3,620
  • 1
  • 19
  • 19
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;
    }
  }  
});
Ninjanoel
  • 2,864
  • 4
  • 33
  • 53
lmcDevloper
  • 332
  • 2
  • 8
  • 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'); }` – Ninjanoel Dec 07 '16 at 16:36
  • What about elements which are hidden beneath other items? – Questionnaire Feb 24 '20 at 07:58
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.

gpl
  • 1,380
  • 2
  • 8
  • 24
No one
  • 1,130
  • 1
  • 11
  • 21
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
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alireza
  • 100,211
  • 27
  • 269
  • 172
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/

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun Karnawat
  • 575
  • 10
  • 21
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.

Oriol
  • 11,660
  • 5
  • 35
  • 37
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
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
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Sky Yip
  • 1,059
  • 12
  • 10
13

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
L Y E S - C H I O U K H
  • 4,765
  • 8
  • 40
  • 57
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  
   // };  
Sangeet Shah
  • 3,079
  • 2
  • 22
  • 25
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; }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Disapamok
  • 1,426
  • 2
  • 21
  • 27
12
$( "div:visible" ).click(function() {
  $( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
  $( "div:hidden" ).show( "fast" );
});

API Documentation: visible Selector

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Wolfack
  • 2,667
  • 1
  • 26
  • 50
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();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdul Aziz Al Basyir
  • 1,104
  • 13
  • 28
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'
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Antoine Auffray
  • 1,283
  • 1
  • 17
  • 33
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>
Sahil Thummar
  • 1,926
  • 16
  • 16
7

Using hidden selection you can match all hidden elements

$('element:hidden')

Using Visible selection you can match all visible elements

$('element:visible')
Hasee Amarathunga
  • 1,901
  • 12
  • 17
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
}
Vicky P
  • 553
  • 6
  • 12
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

BaseZen
  • 8,650
  • 3
  • 35
  • 47
Profesor08
  • 1,181
  • 1
  • 13
  • 20
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Muhammad
  • 6,725
  • 5
  • 47
  • 54
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;
}
mike rodent
  • 14,126
  • 11
  • 103
  • 157
Brane
  • 3,257
  • 2
  • 42
  • 53
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Peter Wone
  • 17,965
  • 12
  • 82
  • 134
5
isHidden = function(element){
    return (element.style.display === "none");
};

if(isHidden($("element")) == true){
    // Something
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Disapamok
  • 1,426
  • 2
  • 21
  • 27
3
if($("h1").is(":hidden")){
    // your code..
}
Sam Hanley
  • 4,707
  • 7
  • 35
  • 63
cbertelegni
  • 423
  • 2
  • 11
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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Aravinda Meewalaarachchi
  • 2,551
  • 1
  • 27
  • 24
2
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>
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
2

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.");
        }
    });
});
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
Swift
  • 790
  • 1
  • 5
  • 19
2
   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{

  }
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Mojtaba Nava
  • 858
  • 7
  • 17
2

The easiest answer to this question is this:

function checkUIElementVisible(element) {
    return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
Enrico König
  • 206
  • 1
  • 13
  • 22
1

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');
  }
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

You can try this:

$(document).ready(function () {
    var view = $(this).is(":visible");
    if (view) {
        alert("view");
        // Code
    } else {
        alert("hidden");
    }
});
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
0
$("someElement").on("click", function () {
    $("elementToToggle").is(":visible");
});
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jun 27 '23 at 14:57
0
if ($(element).is(":visible")) {
    console.log("element is visible");
} else {
    console.log("element is not visible");
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
centralhubb.com
  • 2,705
  • 19
  • 17
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jun 27 '23 at 14:56
-5

You can hide any element with class d-none if you're using Bootstrap.

if (!$("#ele").hasClass("d-none")) {
    $("#ele").addClass("d-none"); //hide
}
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
udorb b
  • 135
  • 3