404

In jQuery, there are .hide() and .show() methods which sets the CSS display: none setting.

Is there an equivalent function which would set the visibility: hidden setting?

I know I can use .css() but I prefer some function like .hide() or so. Thanks.

2

6 Answers 6

481

You could make your own plugins.

jQuery.fn.visible = function() {
    return this.css('visibility', 'visible');
};

jQuery.fn.invisible = function() {
    return this.css('visibility', 'hidden');
};

jQuery.fn.visibilityToggle = function() {
    return this.css('visibility', function(i, visibility) {
        return (visibility == 'visible') ? 'hidden' : 'visible';
    });
};

If you want to overload the original jQuery toggle(), which I don't recommend...

!(function($) {
    var toggle = $.fn.toggle;
    $.fn.toggle = function() {
        var args = $.makeArray(arguments),
            lastArg = args.pop();

        if (lastArg == 'visibility') {
            return this.visibilityToggle();
        }

        return toggle.apply(this, arguments);
    };
})(jQuery);

jsFiddle.

14
  • @Tomas You'd have to shadow toggle() which could break other scripts. If you wanted, you could add an extra argument to toggle() to specify whether visibility or display should be toggled. I'd just use the custom one in my last example, however. :)
    – alex
    Commented Mar 8, 2012 at 8:49
  • Could you post an example on how to support additional parameters of show (speed, easing, callback)?
    – georg
    Commented Mar 8, 2012 at 8:57
  • 11
    It's superflous if you look at it that way, but there is a purpose. If this is concatenated to another script with a (function() { })() or similar, ASI won't kick in because it looks like a function invocation. Try this, then remove the !.
    – alex
    Commented Mar 9, 2012 at 11:21
  • 1
    @NoBugs Automatic Semi-colon Insertion. I wrote a blog post about it here.
    – alex
    Commented Jul 24, 2013 at 22:33
  • 1
    @VishalSakaria It's not really a well-defined term as far as I know, so it should be okay to use it here.
    – alex
    Commented May 15, 2015 at 0:27
121

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

4
  • 1
    Good point, just a force of habit. Thanks. +1 to alex's answer! Commented Mar 8, 2012 at 8:29
  • Just curious, what's the point in wrapping these two functions in the (function($) {...}(jQuery)); wrapper? I've never defined my own functions in jQuery before, I have always just defined functions in straight JavaScript.
    – VoidKing
    Commented May 14, 2013 at 13:24
  • 3
    @VoidKing - It's just the "best practice" for jQuery plugins as per the docs. It allows you to use the $ identifier inside the function, even if it refers to something else in the parent scope. Commented May 14, 2013 at 13:32
  • jQuery actually has a built in toggleClass() method for this :) jqueryui.com/toggleClass Feel free to check out the example I shared in my answer below stackoverflow.com/a/14632687/1056713 Commented May 4, 2017 at 21:33
61

An even simpler way to do this is to use jQuery's toggleClass() method

CSS

.newClass{visibility: hidden}

HTML

<a href="#" class=trigger>Trigger Element </a>
<div class="hidden_element">Some Content</div>

JS

$(document).ready(function(){
    $(".trigger").click(function(){
        $(".hidden_element").toggleClass("newClass");
    });
});
2
  • 1
    I like this approach. It's less self-contained because it requires separate stylesheet, but it helps keep all style information in the stylesheets which is where it should belong. If you wanted to disable the visibility you could change a css tag in one place instead of changing all your js code.
    – vaughan
    Commented Feb 9, 2014 at 4:31
  • 25
    For those using bootstrap, this class is called invisible.
    – user239558
    Commented Sep 23, 2014 at 20:54
27

If you only need the standard functionality of hide only with visibility:hidden to keep the current layout you can use the callback function of hide to alter the css in the tag. Hide docs in jquery

An example :

$('#subs_selection_box').fadeOut('slow', function() {
      $(this).css({"visibility":"hidden"});
      $(this).css({"display":"block"});
});

This will use the normal cool animation to hide the div, but after the animation finish you set the visibility to hidden and display to block.

An example : http://jsfiddle.net/bTkKG/1/

I know you didnt want the $("#aa").css() solution, but you did not specify if it was because using only the css() method you lose the animation.

3

Pure JS equivalent for jQuery hide()/show() :

function hide(el) {
    el.style.visibility = 'hidden';    
    return el;
}

function show(el) {
    el.style.visibility = 'visible';    
    return el;
}

hide(document.querySelector(".test"));
// hide($('.test')[0])   // usage with jQuery

We use return el due to satisfy fluent interface "desing pattern".

Here is working example.


Below I also provide HIGHLY unrecommended alternative, which is however probably more "close to question" answer:

HTMLElement.prototype.hide = function() {
    this.style.visibility = 'hidden';  
    return this;
}

HTMLElement.prototype.show = function() {
    this.style.visibility = 'visible';  
    return this;
}

document.querySelector(".test1").hide();
// $('.test1')[0].hide();   // usage with jQuery

of course this not implement jQuery 'each' (given in @JamesAllardice answer) because we use pure js here.

Working example is here.

3

Here's one implementation, what works like $.prop(name[,value]) or $.attr(name[,value]) function. If b variable is filled, visibility is set according to that, and this is returned (allowing to continue with other properties), otherwise it returns visibility value.

jQuery.fn.visible = function (b) {
    if(b === undefined)
        return this.css('visibility')=="visible";
    else {
        this.css('visibility', b? 'visible' : 'hidden');
        return this;
    }
}

Example:

$("#result").visible(true).on('click',someFunction);
if($("#result").visible())
    do_something;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.