Skip to content

Instantly share code, notes, and snippets.

@itzg
Created October 26, 2012 03:31
Show Gist options
  • Save itzg/3956710 to your computer and use it in GitHub Desktop.
Save itzg/3956710 to your computer and use it in GitHub Desktop.
Open jQuery UI menu on button click
// Create and hide the menu initially
var menu = $("ul#menu").menu().hide();
$("#openMenuBtn).button()
.click(function() {
// Make use of the general purpose show and position operations
// open and place the menu where we want.
menu.show().position({
my: "left top",
at: "left bottom",
of: this
});
// Register a click outside the menu to close it
$( document ).one( "click", function() {
menu.hide();
});
// Make sure to return false here or the click registration
// above gets invoked.
return false;
})
@BillyTom
Copy link

Line #15 should read $(document).on(....)

@DynamoGeek
Copy link

DynamoGeek commented Jun 28, 2016

I know this is a bit old, but I figured I'd throw in a bit of an explanation related to line 15.

Since line 15 is inside the .click function to open the menu, it adds a listener to the document on each click/open of the menu.

.one is just like .on, but it removes the listener in question after its first invocation. When the menu is brought back into existence by another click, a new listener will be attached to the document.

It ends up being an easy way to create an encapsulated chunk of code that's easy to understand in a gist.

http://api.jquery.com/one/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment