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?
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 !==
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.
To detect click outside div using JavaScript, we can check if e. target doesn't equal the inner element. document. getElementById("outer-container").
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(); }; });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With