Using jQuery toggle() to Show and Hide Text
Posted on February 28, 2014 in jQuery by Matt Jennings


I’m going to use the HTML below to show how to click a Read more… link (also know as the .showhide element in the code below) that will display hidden text. Then, you’ll be able to click the .showhide element again to hide the text displayed.

<h2>jQuery toggle() Examples</h2>

<h3>Why do we dream?</h3>
<a class="showhide" href="#">Read more...</a>
<div class="morearticle">The human brain is a mysterious little ball of gray matter. After all these years, researchers are still baffled by many aspects of how and why it operates like it does.</div>

<h3>Why can't we manufacture water?</h3>
<a class="showhide" href="#">Read more...</a>
<div class="morearticle">Water is becoming an increasingly important issue in the developed world. But this issue is nothing new for other, less developed nations.</div>


First, I’ll assign the .showhide selector to a variable named showhide. Then I’ll use var showhidetext = showhide.first().text(); to store the text from the first showhide element into a variable named showhidetext.

Finally I’ll assign the .morearticle selector to a morearticles variable.

By assigning the selectors and text of a selector into variables I’m able to use the DRY programming principal to make the code easier to maintain and possibly faster when referencing the same nodes multiple times in a function.

The hide() method is same as applying a display: none; CSS declaration to the morearticles selector variable, which is the text we want hidden before any links are clicked.

The event.preventDefault(); method prevents the browser from scrolling to the top when you click one of the .showhide elements and a # is added to the URL.

After the showhide element is clicked,the next() method finds the next specified sibling, in this case morearticles selector variable. Finally, the toggle() method applies a display: block; CSS declaration to this morearticles selector variable sibling.

When you click on that same showhide element its morearticles sibling now gets a display: none; CSS declaration to hide the text.

The toggleClass() function adds a .show class to the morearticles selector.

Finally, the if else statement changes the showhide link text to Hide when the morearticles element has a CSS rule of display: block; and back to Read more… when it has a CSS rule of display: none;.

See more options for the toggle() method here. You can find a JSFiddle here.

//Anonymous Function Below for Private variables

    var showhide = $(".showhide"),
	showhidetext = showhide.first().text(),
	morearticles = $(".morearticle");






Leave a Reply

To Top ↑