Wednesday, 21 January 2015

Filled Under:

Toggle Visibility With JavaScript/jQuery

Is it possible to toggle the visibility of an element, using the JavaScript/jQuery functions ? [ .hide(), .show() or .toggle(). etc ]
Also, how to test if an element is visible or hidden?

If you are looking for a single element, this simple piece of code will work.
// Checks display:[none|block], ignores visible:[true|false]
$(element).is(":visible");

The hidden selector could also be used:
// Matches all elements that are hidden
$('element:hidden')

And the visible selector:

// Matches all elements that are visible
$('element:visible')
There is another detailed way of doing this:
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});

This could also be achieved using plain JavaScript, & this
Works everywhere
Works for nested elements
Works for CSS and inline styles
Doesn't require a framework

function isRendered(domObj) {

    if ((domObj.nodeType != 1) || (domObj == document.body)) {

        return true;

    }

    if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {

        return isRendered(domObj.parentNode);

    } else if (window.getComputedStyle) {

        var cs = document.defaultView.getComputedStyle(domObj, null);

        if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {

            return isRendered(domObj.parentNode);

        }

    }

    return false;

}

These are also some useful jQuery Methods,

$('.target').toggle();

$('.target').slideToggle();

$('.target').fadeToggle();

0 comments:

Post a Comment