Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery click off element event

I have a floating div that gets displayed, and I want it to be hidden when the user clicks off the div. This would be similar to the .hover() function callback when hovering off an element. Only I want to do this for click.

I tried just setting a click event for the body, which would hide the div, but that gave unexpected results.

Anyone have ideas on how I could easily do this?

like image 354
Nic Hubbard Avatar asked Sep 14 '09 20:09

Nic Hubbard


People also ask

How do you trigger an event when clicking outside the Element?

Trigger Event When Clicking Outside an Element with jQuery to add a div and we want to detect whether we clicked outside of it. Then we write: $('html'). click((e) => { if (e.target.id !==

How do I detect a click outside an element JS?

To detect click outside element with JavaScript, we can use the element's contains method. const specifiedElement = document. getElementById("a"); document. addEventListener("click", (event) => { const isClickInside = specifiedElement.

How do I know if I clicked outside a div?

To detect click outside div using JavaScript, we can check if e. target doesn't equal the inner element. document. getElementById("outer-container").


2 Answers

If you want to clear the div when you click somewhere else in the page, you can do something like:

$('body').click(function(event) {     if (!$(event.target).closest('#myDiv').length) {         $('#myDiv').hide();     }; }); 
like image 104
David Bennett Avatar answered Oct 18 '22 04:10

David Bennett


Another, possibly simpler, option would be to add a transparent div between the floating DIV and the rest of the page.

A simple click event on the transparent DIV could handle the hiding, and it would avoid the issues you are encountering with the click event.

like image 33
PhillFox Avatar answered Oct 18 '22 05:10

PhillFox