Suppose I have one div in my page. how to detect the user click on div content or outside of div content through JavaScript or JQuery. please help with small code snippet. thanks.
Edit: As commented in one of the answers below, I only want to attach an event handler to my body, and also want to know which element was clicked upon.
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.
Detecting an outside click of a functional component Let's build an HTML tooltip by creating a React functional component named InfoBox . The tooltip will appear when the user clicks a button, and it will be closed if the user clicks outside of the tooltip component.
addEventListener('click', function(e){ if (document. getElementById('clickbox'). contains(e. target)){ // Clicked in box } else{ // Clicked outside the box } });
Here's a one liner that doesn't require jquery using Node.contains:
// Get arbitrary element with id "my-element" var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element'); // Listen for click events on body document.body.addEventListener('click', function (event) { if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) { console.log('clicked inside'); } else { console.log('clicked outside'); } });
If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true
) so this snippet should always work.
Browser support seems to cover pretty much everything according to that MDN page as well.
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