[jquery] jQuery `.is(":visible")` not working in Chrome

if ($("#makespan").is(":visible") == true) { 
    var make = $("#make").val(); 
}
else {
    var make = $("#othermake").val(); 
}

Make:<span id=makespan><select id=make></select><span id=othermakebutton class=txtbutton>Other?</span></span><span id=othermakespan style="display: none;"><input type=text name=othermake id=othermake>&nbsp;-&nbsp;<span id=othermakecancel class=txtbutton>Cancel</span></span>

The above code runs smooth in Firefox, but doesn't seem to work in Chrome. In Chrome it shows .is(":visible") = false even when it is true.

I am using following jQuery version: jquery-1.4.3.min.js

jsFiddle Link: http://jsfiddle.net/WJU2r/4/

This question is related to jquery google-chrome

The answer is


If an item is child of an item that is hidden is(":visible") will return true, which is incorrect.

I just fixed this by added "display:inherit" to the child item. This will fixed it for me:

<div class="parent">
   <div class="child">
   </div>
<div>

and the CSS:

.parent{
   display: hidden;
}
.child{
   display: inherit;
}

Now the item can be effectively switched on and off by changing the visibility of the parent, and $(element).is(":visible") will return the visibility of the parent item


Generally i live this situation when parent of my object is hidden. for example when the html is like this:

    <div class="div-parent" style="display:none">
        <div class="div-child" style="display:block">
        </div>
    </div>

if you ask if child is visible like:

    $(".div-child").is(":visible");

it will return false because its parent is not visible so that div wont be visible, also.


There is a weird case where if the element is set to display: inline the jQuery check for visibility fails.

Example:

CSS

#myspan {display: inline;}

jQuery

$('#myspan').show(); // Our element is `inline` instead of `block`
$('#myspan').is(":visible"); // This is false

To fix it you can hide the element in jQuery and than show/hide or toggle() should work fine.

$('#myspan').hide()
$('#otherElement').on('click', function() {
    $('#myspan').toggle();
});

If you read the jquery docs, there are numerous reasons for something to not be considered visible/hidden:

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.

http://api.jquery.com/visible-selector/

Here's a small jsfiddle example with one visible and one hidden element:

http://jsfiddle.net/tNjLb/


I don't know why your code doesn't work on chrome, but I suggest you use some workarounds :

$el.is(':visible') === $el.is(':not(:hidden)');

or

$el.is(':visible') === !$el.is(':hidden');  

If you are certain that jQuery gives you some bad results in chrome, you can just rely on the css rule checking :

if($el.css('display') !== 'none') {
    // i'm visible
}

Plus, you might want to use the latest jQuery because it might have bugs from older version fixed.


I assume it has something to do with a quirk in our HTML because other places on the same page work just fine.

The only way I was able to solve this problem was to do:

if($('#element_id').css('display') == 'none')
{
   // Take element is hidden action
}
else
{
   // Take element is visible action
}

A cross browser/version solution to determine whether an element is visible, is to add/remove a css class to the element on show/hide. The default(visible) state of the element could be for example like this:

<span id="span1" class="visible">Span text</span>

Then on hide, remove the class:

$("#span1").removeClass("visible").hide();

On show, add it again:

$("#span1").addClass("visible").show();

Then to determine whether the element is visible, use this:

if ($("#span1").hasClass("visible")) { // do something }

This also solves the performance implications, which may occur on heavy usage of the ":visible" selector, which are pointed in jQuery's documentation:

Using this selector 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.

Official jQuery API Documentation for ":visible" selector


This is the piece of code from jquery.js which executes when is(":visible") is called :

if (jQuery.expr && jQuery.expr.filters){

    jQuery.expr.filters.hidden = function( elem ) {
        return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
    };

    jQuery.expr.filters.visible = function( elem ) {
        return !jQuery.expr.filters.hidden( elem );
    };
}

As you can see, it uses more than just the CSS display property. It also depends on the width and height of content of the element. Hence, make sure the element has some width and height. And for doing this, you may need to set the display property to "inline-block" or "block"


I added next style on the parent and .is(":visible") worked.

display: inline-block;


I need to use visibility:hidden insted of display:none because visibility takes events, while display does not.

So I do .attr('visibility') === "visible"


Internet Explorer, Chrome, Firefox...

Cross Browser function "isVisible()"

//check if exist and is visible
function isVisible(id) {
    var element = $('#' + id);
    if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
        return true;
    } else {
        return false;
    }
}

Full example:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
        <script type="text/javascript">
            //check if exist and is visible
            function isVisible(id) {
                var element = $('#' + id);
                if (element.length > 0 && element.css('visibility') !== 'hidden' && element.css('display') !== 'none') {
                    return true;
                } else {
                    return false;
                }
            }

            function check(id) {
                if (isVisible(id)) {
                    alert('visible: true');
                } else {
                    alert('visible: false');
                }
                return false;
            }
        </script>

        <style type="text/css">
            #fullname{
                display: none;
            }
            #vote{
                visibility: hidden;
            }
        </style>
        <title>Full example: isVisible function</title>
    </head>
    <body>
        <div id="hello-world">
            Hello World!
        </div>
        <div id="fullname">
            Fernando Mosquera Catarecha
        </div>
        <div id="vote">
            rate it!
        </div>
        <a href="#" onclick="check('hello-world');">Check isVisible('hello-world')</a><br /><br />
        <a href="#" onclick="check('fullname');">Check isVisible('fullname')</a><br /><br />
        <a href="#" onclick="check('vote');">Check isVisible('vote')</a>
    </body>
</html>

Regards,

Fernando


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 google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?