Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Creating a themeable jQuery UI Menu

4.00/5 (1 vote)
22 Mar 2013CPOL1 min read 11K  
Simple example of a menu styled with jQuery UI themes

Because I'm not very good at designing, I decided to base the style of the new version of MediaCommMVC completely on jQuery UI themes.

I started with the menu and was quite sure I would find a ready to use menu which offers a second level fly out and supports jQuery themes. But none of the hundreds of menu examples I found supported jQuery UI themes (maybe I just missed it?). There is a menu() function in jQuery UI 1.8 which belongs to the autocomplete widget. But its style doesn't really fit in the overall color scheme of the themes.

Not really being interested in creating a menu widget from scratch, I looked at the jQuery UI samples to find components I could reuse. Putting aside the fly-out behavior, the buttonset seemed like a good choice regarding the theme support. The first level menu can be created with just a few radio buttons and a single jQuery call:

HTML
<script type="text/javascript">
    $(function () {
        $("#mainNav").buttonset();
    });
</script>
<nav id="mainNav">
    <input type="radio" id="radio1" name="menu" />
       <label for="radio1">Menu Item 1</label>        
    <input type="radio" id="radio2" name="menu" />
        <label for="radio2">Menu Item 2</label>  
    <input type="radio" id="radio3" name="menu" />
        <label for="radio3">Menu Item 3</label>
</nav>

To add a level 2 fly out menu, I wrapped a menu item in a div and included nested radio buttons:

HTML
<div class="menu-item">
    <input type="radio" id="radio2" name="menu" />
    <label for="radio2">Menu Item 2</label>
    <div class="hover-menu">
        <div class="menu-item">
            <input type="radio" id="radio2Sub1" name="subMenu2" />
            <label for="radio2Sub1">sub menu item 1</label>
        </div>
        <div class="menu-item">
            <input type="radio" id="radio2Sub2" name="subMenu2" />
            <label for="radio2Sub2">sub menu item 2</label>
        </div>
    </div>
</div>

The following CSS code makes the sub menu visible on hover:

CSS
#mainNav .menu-item { display: inline; }
 
#mainNav .menu-item .hover-menu { display: none; }
 
#mainNav .menu-item:hover .hover-menu
{
    display: block;
    position: absolute;
    left: 0;
    top: 28px;
}
 
#mainNav .menu-item:hover { position: relative; }

The result may look like this:

Image 1

You can try it by downloading the sample.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)