+ 1
[SOLVED] Hiding a <ul> popup menu when the document is clicked elsewhere, where the <ul> menu visibility is toggled by a button.
Hi SoloLearners, So in the following page I have a button that toggles visibility of a menu (basically an unordered list <ul> element). I want the menu to automatically disappear when the document is clicked anywhere without having to click the toggling button. I tried to add event listener of "blur" event for the button, but with that, the menu just won't work anymore, it did hide the menu automatically though, How do I go about it, please guide me. Thank you in advance đ https://code.sololearn.com/W23NV6n7KgTw/?ref=app (Solution by ODLNT) https://code.sololearn.com/WJzN1A51NaTJ/?ref=app
4 Answers
+ 1
Ipang you could add a click event to the body element. You would then need to pass the event object to the handler. Using the event object you can check target.tagName(element that was clicked on) and from there determine how to best handle hiding the menu.
+ 2
ODLNT
Thank you! let me try to implement that in the code now ...
+ 2
ODLNT
Thank you again! it works like a charm! đ
+ 1
Ipang
You're welcome. I'm glad I could help.