Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect click outside some elements

I've been looking for some solutions to solve this problem, but nothing helps
Here is my JavaScript code

var specifiedElement = document.getElementById('a');
document.addEventListener('click', function(event) {
  var isClickInside = specifiedElement.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside A and B')
  }
});
div {
  background: #aaa;
  height:2em;
  padding: 1em;
  margin-bottom:10px;
  text-align: center;
}
<div id="a">A</div>
<div id="b">B</div>

(In JS Fiddle: https://jsfiddle.net/1zj9dmq7/)

I want when I click div a/b element, the "alert" function will not run, just running when clicked outside of that 2 elements, and without jQuery
Maybe someone can help me please, Thank You

like image 953
Dafiul Haq Avatar asked May 27 '18 07:05

Dafiul Haq


People also ask

How do I detect a click outside an element jQuery?

Answer: Use the event. target Propertytarget property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.

How does Vue detect click outside component?

We can detect clicks outside an element with Vue. js by creating our own directive. We call Vue. directive with the directive name and an object that has the bind and unbind methods to add the el.

How do I detect a click outside an element angular?

To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs. Approach: Here the approach is to use @HostListener decorator.

How do you hide a div when the user clicks outside of it using JavaScript?

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.


1 Answers

Try this:

var a = document.getElementById('a');
var b = document.getElementById('b');

document.addEventListener('click', function(event) {
  var isClickInside = a.contains(event.target)||b.contains(event.target);
  if (!isClickInside) {
    alert('You clicked outside A and B')
  }
});

Demo: https://jsfiddle.net/1zj9dmq7/1/

like image 192
K K Avatar answered Oct 05 '22 11:10

K K