Wednesday, November 27, 2013

jQuery UI: Highlight Selected Menu Item

The jQuery UI menu widget doesn't actually show the user which item they've clicked. It's helpful, however, if the user knows what they're looking at. Selecting a menu item will probably change the content elsewhere on the page, and the last thing clicked should give an indication of what we're looking at. With the select event, we can change the display state of the selected menu item.

Here, the selected menu item has the ui-state-highlight applied to it. This is all performed in the select event callback function, as illustrated here. Let's take a look at what this function does.

$( this ).find( "a.ui-state-highlight" )
         .removeClass( "ui-state-highlight" );
ui.item.find( "> a" )
       .addClass( "ui-state-highlight ui-corner-all" );     

Within the handler the this context refers to the menu as a whole — not the selected list item. So the first thing we want done is to remove the ui-state-highlight class from and previously-selected items. Next, we refer to the ui event data for the item that was just selected, and add the relevant classes. Note too that this customization involves a bit of CSS in order to work correctly.

.ui-menu .ui-menu-item {
    margin: 1px 0;
    border: 1px solid transparent;

.ui-menu .ui-menu-item a.ui-state-highlight { 
    font-weight: normal; 
    margin: -1px; 

The .ui-menu .ui-menu-item selector adds a transparent border to all menu items. This is because the ui-state-highlight class defines a border, and so we need to account for the space i'll occupy once applied. The .ui-menu .ui-menu-item a.ui-state-highlight overrides the font-weight and performs a minor position adjustment. With these CSS overrides in place, the highlighted items will appear as a seamless part of the menu widget.