9

I have a variable called object. How can I check with JavaScript if it is visible?

I tried !object.getAttribute("dislay", "none")... but that doesn't work.

Could somebody help me please?

Thank you!

Yves M.
  • 29,855
  • 23
  • 108
  • 144
Denise
  • 1,453
  • 4
  • 14
  • 14
  • 2
    Does this answer your question? [Check if element is visible in DOM](https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom) – Mahozad Oct 26 '22 at 12:43

6 Answers6

20
function isvisible(obj) {
  return obj.offsetWidth > 0 && obj.offsetHeight > 0;
}

as it's implemented in JQuery.

Andrey
  • 1,495
  • 17
  • 14
11

If you use jQuery, the following will return true if the object is visible:

$(object).is(':visible');

If not, you can try these:

if (object.style['display'] != 'none')

But this will work only if display:none has been set explicitly on this object.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
  • +1: As much as I'm normally against throwing jQuery at every JavaScript problem under the sun, especially for rendering issues it's IMO simply not worth reinventing the wheel without making it at least significantly better. – Horst Gutmann Jan 25 '11 at 15:52
2

To get value of a display style using javascript you can use:

IE:

document.getElementById('mydiv').currentStyle.display
or
object.currentStyle.display

Others:

document.getElementById('mydiv').getComputedStyle('display')
or
object.getComputedStyle('display')
KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
1
if (object.style.visibility <> 'visible' || object.style.display == 'none') 

If it doesn't work, try to use

 if (object.currentStyle.visibility <> 'visible' || object.currentStyle.display == 'none')
vmg
  • 9,920
  • 13
  • 61
  • 90
  • 1
    I've looked around a bit and can't find an explanation of what the "<>" syntax is. I assume from context it tests for inequality, but why not just use "!="? Does this do something different? – Addem Aug 30 '18 at 22:32
0

Doesn't look like you're using the getAttribute method correctly. Try taking a look at this.

Kyle
  • 4,261
  • 11
  • 46
  • 85
0

Here is the working version: http://jsfiddle.net/PEA4j/

<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            alert("Is #foo1 visible: " + $("#foo1").is(":visible") + "\nIs #foo2 visible: " + $("#foo2").is(":visible"));

        });
    </script>
</head>
<body>
<div id="foo1" style="display:none">foo1 display none</div>
<div id="foo2">foo2 no display property;</div>
</body>
</html>
M.Nadeem Shaikh
  • 116
  • 1
  • 8