onClickOut() - Detecting Clicks Outside an Element (JavaScript)

In JavaScript it's straightforward to detect click and touch events, but detecting clicks outside an element, say, to automatically close menu's and floating DIV's, needs a bit of code to make it possible. The following solution is from Earkite's UI code, which I've rewritten into a single function that can be used out of the box.

Try it: Show DIV

Enable onClickOut event on any element with just one line:

outsideRelatives are elements outside the target that must not trigger the click-out event when clicked. You must include buttons and links that toggle the display of the target element, or else the click-out event will be triggered, preventing their normal function.

Here's the full code that you can copy-paste. You can also download it as a JS file.

Download JS File

Published on March 13, 2019


Comments

Name

Email

Message



Mildon Maducdoc
Software Developer + Musician
Over 10 years of experience in software and audio.


Hi there! Since 2008, I have been sharing my applications and plugins through this website. My audio plugins and virtual instruments have been used by many music makers, producers, voice-over artists, and film-makers. I build tools that can fuel creativity and inspire musicians to make the right kind of noise.