Reputation: 131989
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
?
Upvotes: 8729
Views: 3240572
Reputation: 24682
// 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.
Upvotes: 3
Reputation: 1024
$(".item").each(function() {
if ($(element).css('display') == 'none' ||
$(element).css("visibility") == "hidden") {
// 'element' is hidden
} else {
// 'element' is visibile
}
});
Upvotes: 2
Reputation: 11437
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.
Upvotes: 1113
Reputation: 820
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.");
}
});
});
Upvotes: 4
Reputation:
You can try this:
$(document).ready(function () {
var view = $(this).is(":visible");
if (view) {
alert("view");
// Code
} else {
alert("hidden");
}
});
Upvotes: 3
Reputation:
$("someElement").on("click", function () {
$("elementToToggle").is(":visible");
});
Upvotes: 0
Reputation: 149
You can hide any element with class d-none
if you're using Bootstrap.
if (!$("#ele").hasClass("d-none")) {
$("#ele").addClass("d-none"); //hide
}
Upvotes: -6
Reputation: 2926
if ($(element).is(":visible")) {
console.log("element is visible");
} else {
console.log("element is not visible");
}
Upvotes: 0
Reputation: 3106
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.
Upvotes: 58
Reputation: 146170
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" });
Upvotes: 336
Reputation: 2500
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>
Upvotes: 8
Reputation: 762
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
}
Upvotes: 7
Reputation: 196
The easiest answer to this question is this:
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
Upvotes: 2
Reputation: 1387
expect($("#message_div").css("display")).toBe("none");
Upvotes: 107
Reputation: 8499
$(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>
Upvotes: 90
Reputation: 881
$(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>
Upvotes: 57
Reputation: 2769
$( "div:visible" ).click(function() {
$( this ).css( "background", "yellow" );
});
$( "button" ).click(function() {
$( "div:hidden" ).show( "fast" );
});
API Documentation: visible Selector
Upvotes: 12
Reputation: 92627
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>
Upvotes: 3
Reputation:
isHidden = function(element){
return (element.style.display === "none");
};
if(isHidden($("element")) == true){
// Something
}
Upvotes: 5
Reputation: 878
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{
}
Upvotes: 2
Reputation: 106544
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.
Upvotes: 10291
Reputation: 9964
$('#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):
Upvotes: 159
Reputation: 2003
Using hidden selection you can match all hidden elements
$('element:hidden')
Using Visible selection you can match all visible elements
$('element:visible')
Upvotes: 7
Reputation: 3339
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;
}
Upvotes: 6
Reputation: 1140
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.
Upvotes: 21
Reputation: 2639
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>
Upvotes: 3
Reputation: 5090
<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
Upvotes: 14
Reputation: 7324
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>
Upvotes: 6
Reputation:
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');
}
});
Upvotes: 1
Reputation: 1475
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.
Upvotes: 4