Write jQuery code to show and hide a panel with one button

Description: One button must open the panel if it is closed, and close it if it is open.

Hint:

  • Use .toggle() or .slideToggle().

HTML of the page

<button id="btn">Open / Close</button>
<div id="panel" style="display:none">Panel content</div>

Solution

$('#btn').on('click', function () {
  $('#panel').slideToggle(300);
});

$('#btn').click();
console.log('after click 1: ' + $('#panel').css('display'));
$('#btn').click();
console.log('after click 2: ' + $('#panel').css('display'));
Console output

after click 1: block
after click 2: none

How it works

  • slideToggle() slides the panel down if it is hidden, and up if it is visible.
  • The panel starts hidden, so the first click opens it.

Read Fade and Slide Effects.


Learn more about the similar topics:
Tutorials
jQuery Effects: hide, show and toggle
jQuery Fade and Slide Effects
jQuery animate() Method
jQuery Method Chaining and Callbacks
Exercises & Assignments
Write jQuery code to show and hide a panel with one button
Write jQuery code to make a simple accordion
Write jQuery code to make simple tabs
Interview Questions & Answers
What is method chaining in jQuery?
How do you hide and show an element in jQuery?
How do you use the animate() method in jQuery?
What is a callback function in jQuery and why is it needed in effects?
What is the difference between stop(), finish() and delay() in jQuery?