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)

You need to firstly ensure that jQuery is included in your project and is referenced on your page or master page. I am using a Master Page so I add the reference to that

I keep my jQuery library in a scripts folder so the reference in the head area looks like:

<script src="../../Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>

We then add some HTML into the content page (or MVC view in this case) like:

<h1>
        Show/Hide using jQuery</h1>
    <a id="showhidetrigger" href="#">show/hide</a>
    <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.