Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery trigger event when click outside the element

$(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.

like image 211
tpae Avatar asked Jul 23 '10 01:07

tpae


People also ask

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

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.

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 you detect a click outside an element react?

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.

How do I hide a div when the user clicks outside?

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.


2 Answers

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(); }); 
  • http://api.jquery.com/event.stopPropagation/

Alternatively, you could return false; instead of using event.stopPropagation();

like image 81
user113716 Avatar answered Sep 21 '22 17:09

user113716


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   } }); 
like image 45
Alexey Sukhikh Avatar answered Sep 24 '22 17:09

Alexey Sukhikh