[SOLVED] Hiding a <ul> popup menu when the document is clicked elsewhere, where the <ul> menu visibility is toggled by a button. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

25th Jun 2022, 1:14 AM
Ipang
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.
25th Jun 2022, 2:49 AM
ODLNT
ODLNT - avatar
+ 2
ODLNT Thank you! let me try to implement that in the code now ...
25th Jun 2022, 6:24 AM
Ipang
+ 2
ODLNT Thank you again! it works like a charm! 👍
25th Jun 2022, 8:33 AM
Ipang
+ 1
Ipang You're welcome. I'm glad I could help.
25th Jun 2022, 1:41 PM
ODLNT
ODLNT - avatar