I have an HTML item for a ‘drop down menu’, structured like this…
<li class="ui-dropdown-list" >
<a href="#">Right Drop Down Menu</a>
<ul>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
<li><a href="#">Item</a></li>
</ul>
</li>
Using jQuery to make this a dropdown list, with the following code.
jQuery.fn.dropdown = function () {
var defaults = {
button: null,
menu: null,
visible: false
};
var options = $.extend(defaults, options);
return this.each(function () {
options.button = $(this);
options.menu = $(this).find("ul");
// when the parent is clicked, determine whether dropdown needs to occur
options.button.click(function () {
options.visible ? lift(options.menu) : drop(options.menu);
options.visible = !options.visible;
});
// drop the menu down so that it can be seen.
function drop(e) {
options.button.addClass("open");
options.menu.show();
}
// lift the menu up, hiding it from view.
function lift(e) {
options.menu.hide();
options.button.removeClass('open');
}
});
};
I am trying to wire it up so that if the user clicks anywhere outside of the menu, it will collapse it. This is proving much more difficult than I anticipated; even trying to use page level events. Any suggestions?
The menu itself never really ‘receives’ focus, so using .blur doesn’t seem to be suiting the purpose.
You can use event bubbling to your advantage here, if a
clickevent bubbles all the way todocumentthen close the menus, if it happens in the menu, stop the bubble so that handler ondocumentdoesn’t get hit, like this:You can see a working demo here 🙂