Question

I have a button that when clicked shows a little non-modal dialog.

Question: How do I detect a click outside the button, so that the dialog can be dismissed?

1 Answers

Set a variable in JavaScript to track that the html element is displayed on the page or that is waiting for a user click. When the html element is displayed or it is waiting for a user click, set the JavaScript variable to true (or 1 if you do not feel too comfortable with Booleans).

In parallel, write a JavaScript function that gets activated whatever a mouse click is detected in the page (you can put a call to this function inside the "onclick" attribute of the BODY element of your page). Inside this JavaScript function, see what is the value of the javascript variable you create to track the element. If its value is true (or 1), you execute the code to dismiss the element. If its value is false (or 0), you ignore the click.

It is important that you reset the value of the element tracking variable each time you dismiss the element so your click detection continue to work after the first click/dismiss event occurrence.


Looking for a job?
Groundswell Cloud Solutions
Vancouver, Canada

Startup (stealth)
London, UK

Accenture
New York

JP/Morgan Chase
Dallas, Texas


Related
How to detect a click outside an HTML element?
Difference between jQuery and Angular
Differences between e.preventDefault(), e.stopPropagation(), and return false;