Show and hide a div on button click using jQuery

How to show and hide a div when clicking on a button.

In the below example, when the 'Show' button is clicked, a hidden div containing an image is shown and the button disappears to show a button to hide the div.

An advantage of using a button instead of using a link is that the page position is kept without having to add extra code to keep the page position.

Click the button to show the div:

The CSS:

This should go in your seperate style sheet, otherwise in your document head between the style tags.
We use 'display:none' with a class, which I've named 'hidden', so that we can apply it to both the button and the div.

.hidden {
display:none;
}

The HTML:

<button class="showButton show">Show div</button>
<button class="hideButton hidden">Hide div</button>

<div class="hidden">
<img src="image.jpg">
</div>

Include jQuery after your closing body tag:

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Then add the javascript:

<script type="text/javascript">

$(function () {

$('.showButton').click(function () {

$('.hidden').show();

$('.show').hide();

});

$('.hideButton').click(function () {

$('.hidden').hide();

$('.show').show();

});

});

</script>