Created
October 26, 2012 03:31
-
-
Save itzg/3956710 to your computer and use it in GitHub Desktop.
Open jQuery UI menu on button click
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}) |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Line #15 should read $(document).on(....)