Make Content Panels Using jQuery

One common design problem is how to display a large amount of content on a page and still make it easily accessible. Often times, a table of contents is used at the top with links within the same page to sections below. This gets pretty unwieldy if you have a lot of content, and splitting it up into multiple pages can be annoying and hard to navigate.

An easy and elegant alternative is to use a dropdown list with content panels made of individual divs. The dropdown acts as the table of contents, and each time a selection is made, only that panel is displayed.

Example:

contentpanel

With a little bit of jQuery and CSS, it’s very simple to create this kind of ui.

First, create a style called hidden to initially hide all the panels but the one you want initially displayed.

<style>

.hidden {display:none;}

</style> 

Then, create your drop down:

<select id="contents">

<option value="div1">Panel #1</option>

<option value="div2">Panel #2</option>

<option value="div3">Panel #3</option>

</select>

Then you create the three divs, marking all with a class called panel to identify them, and the last two also have the class hidden to hide them initially.

<div id="div1" class="panel">

This is panel # 1

</div>
<div id="div2" class="panel hidden"> This is panel # 2 </div> <div id="div3" class="panel hidden"> This is panel # 3 </div>

Now comes the script. I have added a change event handler to the dropdown in the document ready event:

<script language="javascript" type="text/javascript">

    $(document).ready(function () {
        $('#contents').change(function () {
            $('.panel').hide();
            $('#'+$(this).val()).show();

        }); //end change handler

    }); //end ready event

</script>

In the change event handler, I first hide all of the panels by calling .hide(). Then, I get the selected value of the dropdown (which is the this object in the context of the event handler). I stick a # on to the front of it to create the correct selector for jQuery and then call the show() function to display that panel.

A demo of the results is available here.

Leave a Reply

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