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.

Duis sed ligula odio, sed posuere magna. Integer facilisis interdum hendrerit. Nunc eleifend tempus facilisis. Nunc mattis erat ut justo scelerisque sed convallis lorem ultricies. Proin convallis vehicula tincidunt. Fusce ac sapien et odio consectetur condimentum et id elit. Suspendisse potenti.

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> $(document).ready(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;
}