Using the jQuery .toggle() function

Clicking the link below will reveal more content. Clicking a second time will hide it again (a toggle). This example uses the jQuery .toggle() function to show/hide a page element.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec non sem at sapien vulputate fringilla. Curabitur leo leo, tincidunt eu placerat vitae, venenatis ac sem. Ut a dapibus eros. Cras ut imperdiet leo. Nulla fermentum, turpis nec commodo sodales, nibh eros varius diam, sed commodo eros nibh vel est.

Nullam dignissim nibh eget tincidunt volutpat. Etiam quis risus lectus. Vestibulum vel tristique tellus, interdum molestie dui. Sed mattis, metus luctus luctus consectetur, tortor ex tempus turpis, consequat pharetra ligula leo sed felis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam eu ante sodales, porta lorem nec, mattis diam. Vivamus in pharetra ante. Aenean ex mauris, luctus et venenatis vel, suscipit et quam. Vestibulum consequat vestibulum eleifend. Pellentesque libero odio, tincidunt sed neque ac, mollis placerat tellus. Integer vel semper erat, sit amet feugiat quam. Integer nec mauris tortor. Nunc lobortis, lacus sed accumsan fermentum, nunc dolor euismod erat, vitae posuere turpis enim non augue.

Here's the script that does the work:

<!-- load jQuery from Google CDN -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/
jquery.min.js"></script> <script> $(function(){ $("#link a").click(function(){ $("#extra").toggle(); return false; }); }); </script>

Here's the markup at the centre of the action:

<p id="link"><a href="#">More content…</a></p>

<p id="extra">Duis sed ligula odio…</p>

The parent paragraph to the anchor has an id="link" and the hidden paragraph has an id="extra".

This CSS rule simply hides the paragraph when the page loads:

#extra {
display:none;
}

Note: In this example, the script is shown as it would appear if placed in the HTML file and is done only for convenience in demonstrating how it works. The best practice solution would be to place the script in an external file and call it like this:

<script src="filename.js"></script>

jQuery selectors work in exactly the same way as CSS selectors, so the script will work just as well from an external .js file as it will from the .html file.