Testing if a jQuery Object is  Hidden

Using is(":visible") or is(":hidden")

jQuery makes it easy to show, hide or toggle the visibility of a DOM element with the hide(), show() or toggle() methods.

It’s often useful to test if an element has been hidden or shown using jQuery. You can easily do this using the is() method to check if an element has a :visible or :hidden state.

// Checks for display:[none|block], ignores visible:[true|false]
$(element).is(":visible")

JavaScript/jQuery

(function($) {
    var $toggler = $('a.toggler');
    var $target = $('div.hidden');
    var $status = $('div.status');

    // Show/hide content
    $toggler.on('click', function(event){
        event.preventDefault();
        $target.toggle();
        updateStatus();
    });

    // Is it hidden, or is it visible?
    updateStatus = function() {

        // Hidden element is visible
        if ( $target.is(':visible') )
            $status.html('div.hidden is now <strong>:visible</strong>');

        // Hidden element is :hidden
        else
            $status.html('div.hidden is now <strong>:hidden</strong>');
    }

    // Initial setup
    $target.hide();
    updateStatus();
})(jQuery);

CSS

.toggler {
    display: inline-block;
    padding: 3px 6px;
    background: green;
    color: white;
    border-radius: 4px;
    margin: 0 0 10px;
    text-decoration: none;
    font-weight: bold;
}
.status {
    margin: 0 0 0 10px;
    display: inline-block;
}
strong { font-weight: bold }
.box {
    padding: 10px 10px 1px;
    border-radius: 4px;
    background: #eee;
    width: 50%;
}
.box h2 {
    font-weight: bold;
    margin: 0 0 10px;
}
.box p {
    margin: 0 0 10px;
}

HTML

<a href="#" class="toggler">Show Content</a>
<div class="status"></div>
<div class="hidden box">
    <h2>JavaScript Stuff</h2>
    <p>Additional content that appears on-demand.</p>
</div>

Meet the Author

Kevin Leary, WordPress Consultant

I'm a custom WordPress web developer and analytics consultant in Boston, MA with 17 years of experience building websites and applications. View a portfolio of my work or request an estimate for your next project.