How to check if the element is visible in my case?

I have a weird issue in my case.

I have something that is hidden but jquery can't find it.

html

<div id='test'>
    <h3>title here</h3>
</div>

css

#test h3 {
   visibility: hidden;
}

js

if (('#test h3').is(':visible')) {
    alert('visible');
}

I am not supposed to get alert box because my h3 tag is hidden but the alert box keep popping up. Can anyone help me this weird issue? Thanks a lot!

Answers


Since hiding the visibility still consumes space, jQuery considers them visible.

Here's a quote from the docs:

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.


If you want to check if the element's visibillity is not set to hidden, use this:

if ( $('#test h3').css('visibility') == 'visible' ) {
    alert('visible');
}

To check for ancestors too, use this:

var visible = true;

$('#test h3').parents().addBack().each(function() {
    if ( $.css(this, 'visibility') != 'visible' ) return visible = false;
});

if ( visible ) {
    // do whatever...
}

You can abstract all that into a reusable filter expression:

jQuery.expr[':']['visible-real'] = function(el) {

    var visible = true;

    $(el).parents().addBack().each(function () {
        if ( $.css(this, 'visibility') != 'visible' ) return visible = false;
    });

    return visible;
};

You can then use it whenever you need it as follows:

if ( $('#test h3').is(':visible-real') ) {
    alert('visible');
}

Here's the fiddle: http://jsfiddle.net/3LGm7/


Need Your Help

The property 'xyz' does not exist on value of [imported] type 'xyz' in Typescript

javascript node.js visual-studio-2012 typescript

I am accessing functions of an imported nodejs module in typescript, and the compiler spews the given error for each method call or property access. This is my declaration:

Problem with semaphores and sem_wait()

c pthreads mutex parallel-processing semaphore

I have a queue structure that is being used by several pthreads. The threads are supposed to dequeue from the queue if it's not empty and then do their business.