Show Hide function

Course- Javascript >

Using plain old JavaScript, showing and hiding page elements usually means manipulating the value of the display and visibility properties of the element’s style object. While that works OK, it can lead to pretty long lines of code:

document.getElementById("elem").style.visibility = 'visible';

You can use jQuery’s show() and hide() methods to carry out these tasks with rather less code. The jQuery methods also offer some useful additional functionality, as you see in the following code examples.

show()

A simple way to make an element or set of elements visible is to call the show() method:

$("div").show(); // makes all <div> elements visible

However, you can also add some additional parameters to spice up the transition.
In the following example, the first parameter "fast" determines the speed of the transition. As an alternative to "fast" or "slow", jQuery is happy to accept a number of milliseconds for this argument, as the required duration of the transition. If no value is set, the transition will occur instantly, with no animation.

The value "slow" corresponds to 600ms, while "fast" is equivalent to 200ms.

The second argument is a function that operates as a callback; that is, it executes once the transition is complete:

$("#elem").show("fast", function() {
// do something once the element is shown
});                 
                 

Here we have used an anonymous function, but a named function works just fine too.

hide()

The hide() method is, of course, the exact reverse of show(), allowing you to make page elements invisible with the same optional arguments as you saw for hide():

$("#elem").hide("slow", function() {
// do something once the element is hidden
});                 
                 

toggle()

The toggle() method changes the current state of an element or collection of elements; it makes visible any element in the collection that is currently hidden and hides any currently being shown. The same optional duration and callback function parameters are also available to toggle().

$("#elem").toggle(1000, function() {
// do something once the element is shown/hidden
});                 
                 
Remember that the show(), hide(), and toggle() methods can be applied to collections of elements, so the elements in that collection will appear or disappear all at once.