CSS
#toggle {
display: none
}
jQuery
$(document).ready(function() {
$('button').on('click', function() {
$('#toggle').slideToggle();
});
});
A brief explanation:
$('button')
selects the button
element.
$('button').on('click',
is used to attach a click event handler to the button
.
The callback function within on()
will be executed after a click on the button
.
$('#toggle')
selects the div
with the ID of toggle.
$('#toggle').slideToggle()
creates a sliding effect (up-down) on the div
when the button is clicked.
Note
Make sure your code is placed inside the jQuery DOM ready function, as shown below:
$(document).ready(function() {
// your code
})
In short
$(function() {
// your code
});
Since this is JavaScript code, it should be enclosed within the <script>
tags. For example:
<script type="text/javascript">
$(document).ready(function() {
$('button').on('click', function() {
$('#toggle').slideToggle();
});
});
</script>
If you are placing the code in an external file, remember to include it within the <head>
tag like so:
<script type="text/javascript" src="src_to_script"></script>
In response to comment
Can the button disappear after the first click?
Yes, it can. Try the following code:
$(document).ready(function() {
$('button').on('click', function() {
$(this).hide(); // makes the button disappear after the first click
$('#toggle').slideToggle();
});
});