Search code examples
javascriptjqueryjquery-uijquery-ui-menu

Trouble Understanding jQuery-UI Popup Menu


I'm trying to figure out how to make a pop-up menu using the jQuery UI menu widget.

After searching around, I finally found the following demo that does what I want:

http://view.jqueryui.com/menubar/demos/popup/popup-menu.html

However, I am having a little trouble understanding this demo. For example:

  1. What is making the menu hidden before any of the buttons are clicked?
  2. What is causing the menu to close when it's open and I click somewhere else on the page?

Any help appreciated.


Solution

  • I believe this may be what you're looking for. When you call .menu(), lots of things are triggered in the _create() function (as Derek said), like setting class names etc. Then, at lines 123-135 in jquery.ui.menu.js, this happens:

        this.refresh();
    
        // Clicks outside of a menu collapse any open menus
        this._on( this.document, {
            click: function( event ) {
                if ( !$( event.target ).closest( ".ui-menu" ).length ) {
                    this.collapseAll( event );
                }
    
                // Reset the mouseHandled flag
                mouseHandled = false;
            }
        });
    

    The second part makes sure all menus are collapsed when the user clicks on the page (this.document) outside a menu (.ui-menu): this.collapseAll() is called, which calls this._close(), which in turn calls hide(). This should answer your second question.

    As for your first question, The first thing the refresh() function does is:

        // Initialize nested menus
        var menus,
            icon = this.options.icons.submenu,
            submenus = this.element.find( this.options.menus + ":not(.ui-menu)" )
                .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" )
                .hide()
                .attr({
                    role: this.options.role,
                    "aria-hidden": "true",
                    "aria-expanded": "false"
                });
    

    This finds all submenus not previously initialized (in this case all of them since we're coming from _create()) and initializes them, which includes hiding them.