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?
.is(":not(':hidden')") /*if shown*/ :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? :)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; } } }); var items = jQuery('.selector'); if (items.length == 0 || !items.isVisible()) { alert('item is not 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:
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.
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 } 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 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.
You can use this:
$(element).is(':visible'); $(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> 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.
if($('.element').is(':hidden')) { // Do something } <script> if ($("#myelement").is(":visible")){alert ("#myelement is visible");} if ($("#myelement").is(":hidden")){alert ("#myelement is hidden"); } </script> $("#myelement div:visible").each( function() { //Do something }); This is how jQuery implements this feature:
jQuery.expr.filters.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; 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
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 // }; $( "div:visible" ).click(function() { $( this ).css( "background", "yellow" ); }); $( "button" ).click(function() { $( "div:hidden" ).show( "fast" ); }); API Documentation: visible Selector
Use any of visible Selector or hidden Selector to check visiblity:
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> 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
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> 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; } 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.
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.
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."); } }); }); 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> 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> You can try this:
$(document).ready(function () { var view = $(this).is(":visible"); if (view) { alert("view"); // Code } else { alert("hidden"); } }); // One element let isVisible = $("#myButton")[0].checkVisibility(); // Returns true or false // Multiple elements $("div").each((i, el) => if (el.checkVisibility()) { /* el is visible... */ }); The new Element.checkVisibility() checks a variety of factors for visibility, including display:none, visibility, content-visibility, and opacity. You can specify those options:
let isVisible = $("#myButton")[0].checkVisibility({ opacityProperty: true, // Check CSS opacity property too visibilityProperty: true // Check CSS visibility property too }); See the answer for plain/vanilla JavaScript for more information.
$(element).is(":visible")works for jQuery 1.4.4, but not for jQuery 1.3.2, under Internet Explorer 8. This can be tested using Tsvetomir Tsonev's helpful test snippet. Just remember to change the version of jQuery, to test under each one.