Finding if element is visible (JavaScript )

Devon Bernard picture Devon Bernard · Apr 27, 2013 · Viewed 64.9k times · Source

I have a javascript function that tries to determine whether a div is visible and does various processes with that variable. I am successfully able to swap an elements visibility by changing it's display between none and block; but I cannot store this value...

I have tried getting the elements display attribute value and finding if the the element ID is visible but neither has worked. When I try .getAttribute it always returns null; I am not sure why because I know that id is defined and it has a display attribute.

Here is the code of the two different methods I have tried:

var myvar = $("#mydivID").is(":visible");
var myvar = document.getElementById("mydivID").getAttribute("display");

Any guidance or assistance would be greatly appreciated.

Answer

palaѕн picture palaѕн · Apr 27, 2013

Try like this:

$(function () {
    // Handler for .ready() called.
    if ($("#mydivID").is(":visible")) {
        alert('Element is visible');
    }
});

FIDDLE

Please make sure to include the jQuery file inside the head tag, as follows

<head>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>