Show and Hide a div using jQuery

You may find yourself wanting to show and hide a section of your page from a button or a link. This is very easy with a little jQuery.

All you need to do is have a triggering object (an a tag in my example) and a target object (a div in my example)

<p><a href="#" id="showhidetrigger">show/hide</a></p>

<div id="showhidetarget">This is the box that is hidden and shown.</div>

<script type="text/javascript">
        $(document).ready(function () {

            $('a#showhidetrigger').click(function () {

You can see the trigger a tag named showhidetrigger and the target div called showhidetarget and our jQuery script at the bottom.

The $(document).ready(function () { line is telling jQuery to execute when the page is ready and everything is loaded.

The $(‘#showhidetarget’).hide(); line is hiding the target div initially, and the $(‘a#showhidetrigger’).click(function¬†() { $(‘#showhidetarget’).toggle(400); }); lines are telling the target div to toggle visible and invisible on the click event of the trigger a tag.

The jQuery Toggle method includes a nice smooth transition as well which makes it look great. You can speed up or slow down the transition by increasing or decreasing the transition parameter

Leave a Reply