Show and Hide a Div on Button Click With jQuery

Quick Summary
- A jQuery click handler on the button calls slideToggle, which slides the content div open when hidden and closed when visible.
- Swap in toggle for an instant show and hide, or pass a duration in milliseconds such as slideToggle(200) to change the speed.
- Hide the content with display none in your CSS if it should stay closed until the first click.
A button that shows and hides a block of content is handy for filters, menus and FAQ answers. This version uses jQuery: each click on the button slides a list open or closed. For FAQ answers, HTML’s <details> element also works without a script, as in turning details elements into an accordion. In WordPress, enqueue your script with jquery as a dependency so jQuery is loaded first.
The HTML
The button and the element it controls each need an ID. Here the button is #filter-btn and the content is the #newpost div with a list of links. Replace the empty href values with your own URLs.
<button id="filter-btn">FILTER BUTTON</button>
<div id="newpost">
<ul>
<li><a href="">ITEM 1</a></li>
<li><a href="">ITEM 2</a></li>
<li><a href="">ITEM 3</a></li>
</ul>
</div>The jQuery
(function($) {
"use strict";
// A $( document ).ready() block.
$( document ).ready(function() {
$("#filter-btn").click(function() {
//$("#newpost").toggle();
$("#newpost").slideToggle();
});
});
})(jQuery);.click()attaches a handler to the button, andslideToggle()slides#newpostclosed if it is visible and open if it is hidden.- For an instant show and hide without the animation, use the commented-out
toggle()line instead. - To change the speed, pass a duration in milliseconds, for example
slideToggle(200). - To keep the list hidden until the first click, set
#newposttodisplay: nonein your CSS. - The outer wrapper maps
$tojQuery, which you need in WordPress because it loads jQuery in no-conflict mode.
Live demo
You can try the button and edit the code in the JSFiddle below.
Related articles
- changing a button’s label on click with jQuery: useful for a Show/Hide label on the same button
