I've designed a dropdown menu (in vain of attempting to style an actual <select>
element consistently across browsers), which when clicked, shows an unordered list of dropdown options. This functionality is provided via Knockout.js which uses an observable to check whether the dropdown should be shown or hidden. The DOM structure is here:
<div id="actionsDropdown">
<a data-bind="click: toggleDropdownVisibility, css: { active: showDropdown() == true }">Actions</a>
<ul data-bind="visible: showDropdown">
<li>Option 1</li>
<li>Option 2</li>
</ul>
</div>
And here is my Knockout.js code:
self.showDropdown = ko.observable(false);
self.toggleDropdownVisibility = function () {
console.log(self.showDropdown());
self.showDropdown(!self.showDropdown());
};
This works pretty well, except for a few things.
How can I implement logic to also hide the dropdown when anywhere else on the page is clicked if the dropdown is already visible?
I guess I could bind a click handler to the body
element, but then it'd open it if it were closed, which is obviously not optimal.