Wednesday, July 10, 2013

jQuery UI: Context Menu

I recently discovered the context menu widget, a third-party jQuery UI plugin. It's pretty neat. I like the way it's implemented too. It wraps itself around a menu widget, stored internally, and manages the click events. It'll create the necessary markup for you as well when passed an array of menu item objects, which is nice, because I generally don't want to write markup for a context menu myself - where would I put it? Despite the limited use cases for context menus, at least in my opinion, they can prove useful for certain types of users who know they're there.

For example, to play around with this widget, I added a context menu to each tab in a tabs widget, that allows the user to remove the tab.


And here is the context manu Javascript in action.

$(function() {

    $( "#tabs" ).tabs();

    $( ".ui-tabs" ).contextmenu({

        // We're telling the context menu widget to display
        // each time a tab is right clicked.
        delegate: ".ui-tabs-anchor",

        // The context menu widget takes care of assembling
        // the interanl menu widget for us.
        menu: [
            { 
                title: "Close",
                cmd: "close",
                uiIcon: "ui-icon-close"
            }
        ],

        // Fires when a context menu item is selected.
        select: function( event, ui ) {

            // This is how we know which menu item was 
            // selected.
            if ( ui.cmd !== "close" ) {
                return;
            }

            // The ui object has our target tab anchor that
            // was right-clicked.  Now we can remove the
            // tab, the panel, and refresh the tabs widget.
            var $target = ui.target,
                panel   = $target.closest( "li" )
                                 .remove()
                                 .attr( "aria-controls" );

            $( "#" + panel ).remove();

            $( "#tabs" ).tabs( "refresh" );

        }

    });

});