
Member-only story
The “off” click
Clicking anywhere off an element in Javascript ✋
I don’t know the technical term for this scenario 😅 We’ve likely all encountered it though. That scenario where you’ve bound a click to open or activate something. But, you also want a click bound to clicking anywhere else that closes it.
What is the technical term for that? I’m going to call it the “off” click.
Consider this common example using a side menu. You click the menu button to open the menu. When you go to click off it, you expect it to close. It shouldn’t be the case that it only closes when you click the menu button again.
For those in camp TL;DR, the solution is bind an “off” click method to the document
within your initial click handler. This gets added and removed when necessary. Here’s a demo!
Before we go any further. This isn’t just applicable to the side menu scenario. It could be used in other scenarios you may come across. It is also true, that we could use other methods to close the sliding menu such as a clickable overlay that fills the rest of the page.
A simple side menu
For our example, we are going to use a simple side menu that slides in and out. The menu contains items that allow the user to change the background color of the page.
Basic opening and closing
To open and close the side nav, we will apply a class to the menu element. The class will dictate the transform of the menu element sliding it right and left.
So what might the code look like for this? In the most basic implementation we can toggle the class on the menu element.

But this isn’t ideal. We can open the menu, but the only way to close it is by clicking the menu button again.