$(document).click(function(evt) { var target = evt.currentTarget; var inside = $(".menuWraper"); if (target != inside) { alert("bleep"); } });
I am trying to figure out how to make it so that if a user clicks outside of a certain div (menuWraper), it triggers an event.. I realized I can just make every click fire an event, then check if the clicked currentTarget is same as the object selected from $(".menuWraper"). However, this doesn't work, currentTarget is HTML object(?) and $(".menuWraper") is Object object? I am very confused.
So, for detecting a click outside an element, it would be best if you add a listener to the whole document element. Consequently, the main loop will go up the DOM from the clicked target element to search if the ancestor of that element belongs to the flyout container.
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.
To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.
Just have your menuWraper
element call event.stopPropagation()
so that its click event doesn't bubble up to the document
.
Try it out: http://jsfiddle.net/Py7Mu/
$(document).click(function() { alert('clicked outside'); }); $(".menuWraper").click(function(event) { alert('clicked inside'); event.stopPropagation(); });
Alternatively, you could return false;
instead of using event.stopPropagation();
if you have child elements like dropdown menus
$('html').click(function(e) { //if clicked element is not your element and parents aren't your div if (e.target.id != 'your-div-id' && $(e.target).parents('#your-div-id').length == 0) { //do stuff } });
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