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 () {
            $('#showhidetarget').hide();

            $('a#showhidetrigger').click(function () {
                $('#showhidetarget').toggle(400);
            });
        });
    </script>

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

If you got benefit from this article, feel free to:

ABOUT THE AUTHOR

I’m the Technical Director at Expeed Technology in Adelaide, South Australia. In my day job I work on both Windows and Linux web hosting technologies and Windows and Web .NET development. In my spare time I tinker with video production, photograpy, and all things Azure, including IAAS, PAAS and Serverless. You can find me on Twitter over at @simonholman¬†

Share

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

Related

Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Do NOT follow this link or you will be banned from the site! Scroll to Top