Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to test an element in the DOM

There are a couple of ways I could do this (That I'm aware of).

Test css display

if ($('#foo').css('display') == 'none')

Test the visibility

if ($('#foo').is(':visible'))

In the visibility I can check if the element is there.

Elements are considered visible if they consume space in the document. Visible elements have a width or height that is greater than zero.

Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout.

Source

But, note that in both I can't test the visibility (by the user) because:

Hiding an element can be done by setting the display property to "none" or the visibility property to "hidden". However, notice that these two methods produce different results:

visibility: hidden hides an element, but it will still take up the same space as before. The element will be hidden, but still affect the layout.

display: none hides an element, and it will not take up any space. The element will be hidden, and the page will be displayed as if the element is not there:

Source

So in neither of the examples I test if the element is visible in all senses for the user.

So my question is:

  • What're the differences between the two if's codes from above?
  • What's the best way to test if an element is visible to the user:

Should I have to use something like:

if ($('#foo').is(':visible') && 
    $('#foo').css('opacity') > 0 && 
    $('#foo').css('visibility') != 'hidden')
like image 281
Michel Ayres Avatar asked May 14 '12 19:05

Michel Ayres


1 Answers

I think your best bet is to implement a custom function like below and test/improve as new things come up,

$.fn.isReallyVisible = function () { //rename function name as you like..
    return (this.css('display') != 'none' &&
            this.css('visibility') != 'hidden' &&
            this.css('opacity') > 0);
}

The above should be cross browser proof as we are using jQuery .css function (specifically for opacity).

DEMO

like image 87
Selvakumar Arumugam Avatar answered Oct 02 '22 13:10

Selvakumar Arumugam