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 Content</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>

Meet the Author

Kevin Leary, WordPress Consultant

I'm a freelance web developer and WordPress 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.