Toggle the visibility with jQuery

When it comes to quick JavaScriopt effects one of the most common is to hide and show different elements in the DOM. That occurs in almost every site. If there’s a dynamic menu, there’s for sure attached mouse event that shows/hides some sub menus and so on.

Of course you can achieve this in both jQuery and pure JavaScript approaches. If you use JS it’s something like that;

document.getElementById('element_id').style.display = 'block';
document.getElementById('element_id').style.display = 'none';

where the first row shows how to show an element, and the second one how to hide it in turn.

The jQuery way!

With jQuery of course that comes with ease.

$('#element_id').show();
$('#element_id').hide();

The problem is…

when you’d like to change the visibility with only one click over one element.

Let’s assume you’ve one A tag and on click you show a DIV element. In turn when the DIV is already visible, on click over the same A tag you’d like to hide the DIV.

How to make this the hard way?

$('#a_tag_id').click(function() {
    if ( $('#div_id').length > 0 )
        $('#div_id').hide();
    else
        $('#div_id').show();
});

The good news is that you can toggle the visibility with the $.toggle function, which is built-in in jQuery. The same functionality, shown above you can do, simply by that:

$('#a_tag_id').click(function() {
   $('#div_id').toggle();
});

And that is pretty simple and clear.

Note that if you’d like to change the CSS visibility property that toggle function wont work. The toggle is useful only for changing the display CSS property.

One thought on “Toggle the visibility with jQuery

  1. you can also use pure javascript like this:

    document.getElementById(“id”).style.display=document.getElementById(“id”).style.display==”block” ? “none” : “block”;

    I would probably make a variable for the document.get … part.

Leave a Reply

Your email address will not be published. Required fields are marked *