Simple jQuery: Hide/Show elements with .toggle() and .slidetoggle()

The .toggle() and .slideToggle() functions in jQuery are great tools for hiding and displaying information on your websites. Here is a quick guide to the basics of each function with code and examples.

Include jQuery in your page
A simple way to include jQuery is to use a version hosted by Google at Google Libraries API. Copy the ‘path:’ entry (which is a link to the latest version of jQuery) into the head of your HTML page. Also you create the jQuery onload() function below to add your functions.

Example 1 – A Simple Div Toggle
The simplest way to use the .toggle() function is to turn an element on and off using the following code. The div is hidden initially with the inline CSS ‘style=”display:none;”‘.

The jQuery function applies the toggle behaviour to the div (with class ‘toggle1′) which is activated when the link (with id ‘toggle1′) is clicked. The line return false; overrides the standard behavior of the ‘a’ tag and stops the browser returning to the top of the page when clicked. Try it out below:

This time the function is applied to toggle BOTH ‘p’ elements but controlled from the same link. By hiding one element when the page is loaded, the switching effect is achieved by hiding the visible element and showing the hidden element with a single click. Try it out below:

The jQuery function is almost exactly the same as Example 1 but with the addition of a duration. jQuery has 3 standard durations, ‘slow’, ‘normal’ and ‘fast’, built in but you can also specify a number of milliseconds to further customise your script. Remember not to surround these values with quotes in your code. Try it out below:

Example 4 – Toggle with the .slideToggle() function
The slide toggle can be called in the same way as the standard toggle function but, unlike .toggle(), the slideToggle is always animated. Also, rather than expanding from the top left corner as .toggle() does, .slideToggle() slides the element down to it’s defined height over the course of the animation but is always the same width.

In this example the duration is set to ‘fast’ and, when the toggle link is clicked, the element will slide in with a width of 100 pixels (as defined in the CSS of the element). This technique is helpful for having boxes drop in from the top of a page, or as part of an accordion effect. Try it out below: