359

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.

Tomas
  • 52,167
  • 46
  • 207
  • 345
  • 2
    You can implement your own based on `.toggle()` – zerkms Mar 08 '12 at 08:19
  • I'm also a fan of jQuery's toggleClass() method for this :) http://jqueryui.com/toggleClass/ Feel free to check out the example I shared in my answer below http://stackoverflow.com/a/14632687/1056713 – Chaya Cooper May 04 '17 at 21:41

6 Answers6

448

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.

alex
  • 438,662
  • 188
  • 837
  • 957
  • @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 Mar 08 '12 at 08:49
  • Could you post an example on how to support additional parameters of `show` (speed, easing, callback)? – georg Mar 08 '12 at 08:57
  • @thg435 I provided an example of overloading an existing jQuery method. You should be able to adapt the example to what you desire. – alex Mar 08 '12 at 09:51
  • Sorry alex, I misunderstood what `.toogle()` is ... So my first comment here is bogus. The first solution is the one to go. – Tomas Mar 08 '12 at 14:13
  • Just a note - `!` is not necessary if you're using parens. `!function(){}()` or `(function(){})()` make for a function expression, using both is superfluous. – pimvdb Mar 09 '12 at 10:35
  • 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](http://jsfiddle.net/AT8xn/), then remove the `!`. – alex Mar 09 '12 at 11:21
  • 1
    @NoBugs Automatic Semi-colon Insertion. I wrote a [blog post](http://blog.alexanderdickson.com/javascript-semicolons) about it here. – alex Jul 24 '13 at 22:33
  • The first block lacks a bunch of semicolons, please add them. It does work this way, but is considered bad style. – poitroae Aug 18 '13 at 08:00
  • @poitroae Sure, but remember you're free to edit the answer. I'd say it's bad practice to mix styles, which I did. – alex Aug 18 '13 at 11:14
  • this works well when working with google maps, the panel that gmaps loads into has to be visible so it can work out the width/height etc. if your panel is initially set to display:none, the map will not display correctly. setting visibility:hidden though will work and the funcs above allow me to easily manage the visible state with jquery. thank you! – Terry Kernan Sep 13 '13 at 11:43
  • override not over load ;) – Vishal Sakaria May 14 '15 at 09:48
  • 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 May 15 '15 at 00:27
  • jQuery actually has a built in toggleClass() method for this :) http://jqueryui.com/toggleClass/ Feel free to check out the example I shared in my answer below: http://stackoverflow.com/a/14632687/1056713 – Chaya Cooper May 04 '17 at 21:35
  • @ChayaCooper This isn't toggling classes, but toggling visibility. – alex May 08 '17 at 09:33
109

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.

James Allardice
  • 156,021
  • 21
  • 318
  • 304
  • 1
    Good point, just a force of habit. Thanks. +1 to alex's answer! – James Allardice Mar 08 '12 at 08: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 May 14 '13 at 13:24
  • 2
    @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. – James Allardice May 14 '13 at 13:32
  • jQuery actually has a built in toggleClass() method for this :) http://jqueryui.com/toggleClass/ Feel free to check out the example I shared in my answer below http://stackoverflow.com/a/14632687/1056713 – Chaya Cooper May 04 '17 at 21:33
57

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");
    });
});
Nicolas Rojo
  • 593
  • 1
  • 5
  • 14
Chaya Cooper
  • 2,410
  • 1
  • 33
  • 65
  • 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 Feb 09 '14 at 04:31
  • 21
    For those using bootstrap, this class is called invisible. – user239558 Sep 23 '14 at 20:54
26

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.

h3ct0r
  • 675
  • 10
  • 20
2

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.

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
2

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;
Teet Kalm
  • 21
  • 4