Close menu if clicked outside div

I am trying to add a code that will allow me to close Mobile menu if I click outside it or on Close button.

My current code to close a menu is:

function CloseMobileMenu() { var e = document.getElementById("mobile-menu"); = "hidden", = "0" }

So, I want to close div by clicking X button (inside menu div) and outside it.

Thank you.

Your code changes CSS properties on #mobile-menu, which I’m going to assume is correct. What we need to see is the code that actually calls the CloseMobileMenu() function. Or are you asking how to do that?

CloseMobileMenu() is added in .

That is the JS I use to close Menu. No additional JS is used

I’m not sure I understand what you are saying here. Please provide the actual code where this is added in.

If you are talking about adding an inline onClick handler to the button, such as:

<button onclick="CloseMobileMenu()">Close</button>

This will work when they click the close button but it won’t work if they click outside the dialog. You would generally do that by adding a click handler on the body when the dialog is opened and then calling CloseMobileMenu if the click was not on the dialog.

But I am just guessing here because I don’t know what you have done so far.

Let me explain myself.

I have a button that closes a menu
<button onclick="CloseMobileMenu()">Close</button>.

I want to close that menu if someone touches outside menu and only that button.

I have no experience in JS so I will need help with the entire code.

My current JS code to close the menu is:

function CloseMobileMenu() {
    var e = document.getElementById("mobile-menu"); = "hidden", = "0"

Thank you for your help.

I see you have been a member here for quite a while but you say you have no experience in JS, so it sounds like you haven’t completed the JS module here at FCC? Have you considered trying that? There are a ton of good beginner’s books on web development out there as well.

As for the code you have posted, clicking the button should hide the element with id mobile-menu. But I’m still not sure I understand what else you want to do.

I want to close the menu when I click outside of it.

As I mentioned above, you would add a click handler on the document when the dialog initially opens and then close the menu programatically if the click is not on the menu itself.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.