How to detect click outside an element in JavaScript?
Hi everyone! I'm a beginner in JavaScript and I'm writing a dropdown menu. I need it to close when the user clicks anywhere outside the menu itself. I've tried many options, but nothing works correctly.\n\nHere's my current code:\n\n```javascript\nconst menu = document.getElementById('myMenu');\n\ndocument.addEventListener('click', function(event) {\n if (event.target !== menu) {\n menu.style.display = 'none';\n }\n});\n```\n\nThe problem is that the menu closes even when I click on its content (for example, list items or buttons inside). I understand that event.target is the specific element that was clicked, not the menu container itself. How do I properly check that the click was outside the element, including all its child nodes? I need a pure JavaScript solution.
No answers yet.
Log in to leave an answer
Blogs