Javascript/jQuery Tutorials

Lesson 1: Toggle Showing/Hiding Content

How Do You Toggle Showing/Hiding Content?

Let's learn!

Step 1

Firstly, becuase we are working with jQuery, you need to make sure you have the following code at the end of your HTML file, just above the closing body tag to load the jQuery library:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
			

Step 2

Write your HTML file. Below is the code for Arnold Schwarzenegger's toggled bio. The code is the same for the other awesome action stars biographies, just change the content. Pay special attention to the classes, as this will be important for styling and the JavaScript/jQuery code coming next.

<div class="bio">
	<h2>Arnold Schwarzenegger</h2>
	<img src="images/arnie.jpg" alt="picture of Arnold Schwarzenegger">
	<button class="btn-show">Show Bio</button>
	<p class="bio-text">Arnold Alois Schwarzenegger (born July 30, 1947) is an Austrian-American actor, model, producer, director, activist, businessman, investor, writer, philanthropist, former professional bodybuilder, and politician. Schwarzenegger served two terms as the 38th Governor of California from 2003 until 2011.
	</p>
</div>

Step 3

Now you style the code with some CSS.

.bio {
	width: 30%;
	float: left;
	border: 1px solid black;
	padding: 10px;
	margin: 6px;
}

.bio button {
	margin: 6px;
	background-color: #cc3333;
	color: #fff;
	font-size: 16px;
	box-shadow: 5px 5px 15px #000;
}

.bio p {
	margin-top: 10px;
}

Step 4

And we finish off with the JavaScript/jQuery code.

$('.bio-text').hide();

$('.btn-show').click(function() {
	var $this = $(this);
	var theText = $this.next();
	if(theText.is(':visible')) {
		$this.text('Show Bio');
	} else {
		$this.text('Hide Bio');
	}

	theText.slideToggle(500);
});

Check you out, now you can toggle whether content is hidden or shown!