Using jQuery toggle() to Show and Hide Text

by Matt Jennings

HTML

<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>

JavaScript

//Anonymous Function Below for Private variables
(function(){ 
    
    var showhide = $(".showhide"),
    showhidetext = showhide.first().text(),    
    morearticles = $(".morearticle");
    
    $(morearticles).hide();

    $(showhide).click(function(event){
        event.preventDefault();
        $(this).next(morearticles).toggle("slow").toggleClass("show");

        if($(this).next(morearticles).hasClass("show"))
        {      
            $(this).text("Hide");   
        }
        else
        {
            $(this).text(showhidetext);              
        }

    });    

})();