Tag Archives: visible

jQuery: How to Test if a div is Visible Programming 17 JUL 2013

jquery-logoThe wonderful jQuery library actually makes it pretty easy for us to test whether or not a div (or pretty much any other element for that matter) is currently visible, by providing us with a ‘:visible’ selector.

Basically elements are considered visible by jQuery if they consume space in the document, meaning that visible elements have a width or height that is greater than zero. Combining this with the .is filter forms the basis for our test.

In practice:

//assuming a div with id "div1"
$('#div1').show();
alert ($('#div1').is(':visible')); //true
$('#div1').hide();
alert ($('#div1').is(':visible')); //false

Nifty. As always, play with around with it yourself in the awesome JSFiddle online JavaScript playground.

Toggle a Div’s Visibility with jQuery CodeUnit 18 JAN 2011

To toggle an element in terms of visibility, like a DIV for example, is pretty easy with jQuery and its ultra nifty toggle() function.

First, simply declare the div you wish to hide and show, give it an ID and if you want, set the initial display by using a style attribute like display: none;

Then, create a toggle controller element which you will use for the user to click on in order to trigger the DIV display/hide action. Again, this needs a ID attribute at most:

<p style="cursor:pointer" id="togglecontrol">(Show/Hide)</p>
<div style="display:none;" id="toggle">Toggle Me!</div>

Finally, put it all together with some jQuery code:

    $(document).ready(function(){
        $('#togglecontrol').click(function(){
            $('#toggle').toggle();
        });
    });

So now clicking on the toggle control element will run the toggle() function against the DIV, basically showing and hiding it at will!

Nifty.