JQuery Toggle Drop Down Effect
CSS, HTML5, JavaScript, Web Design
jQuery is a pretty amazing JavaScript library. It allows you to do things with JavaScript that were, back in the day, pretty tough to pull off. Today I want to show you how to do a simple toggle drop down effect using jQuery. The first thing you’ll want to do is create a basic HTML page like so:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Toggle Drop Down</title>
<meta charset=”utf-8″>
</head>
<body>
<p>
<span id=”s1″>
Click to slide panel up and down
</span>
</p>
<div id=”d1″>
This part slides up and down
</div>
</body>
</html>
This sets up a span and div tag that will use their ids to receive the user’s click and then respond to it. Next thing we want to do is add the styling that will allow us to see this in action. So add a style tag and that style block inside the head tag:
<style>
#d1, #s1 {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#d1 {
margin: 10px;
padding: 25px;
width: 150px;
height: 150px;
box-shadow:5px 5px 10px #ccc;
}
</style>
Most of this is aesthetic stuff. It just gives the span and div tags dimensions, background colors, aligns the text to the center, gives a border, and things of that nature. Then to the main part of this tutorial. Add this jQuery right under the closing style tag:
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“#s1”).click(function(){
$(“#d1”).slideToggle(“slow”);
});
});
</script>
The first line imports the jQuery library so you can use it.
The document ready statement tells the code contained in the following function to run after the whole page has loaded
The next line says when the tag with the id of s1 is clicked it will run the following function
The function tells the tag with the id of d1 to do a slideToggle() method. This method is a built-in jQuery command that makes the div slide up and down revealing and hiding its contents. All of that is just built into the jQuery language, you don’t have to manually code the animation. When all is said and done, the whole project should look like this:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Toggle Drop Down</title>
<meta charset=”utf-8″>
<style>
#d1, #s1 {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#d1 {
margin: 10px;
padding: 25px;
width: 150px;
height: 150px;
box-shadow:5px 5px 10px #ccc;
}
</style>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>
<script>
$(document).ready(function(){
$(“#s1”).click(function(){
$(“#d1”).slideToggle(“slow”);
});
});
</script>
</head>
<body>
<p>
<span id=”s1″>
Click to slide panel up and down
</span>
</p>
<div id=”d1″>
This part slides up and down
</div>
</body>
</html>
And there you have it, a cool way to show and hide content on a webpage. If you’d like to learn more be sure to check out all of our jQuery Training. Have an amazing day!