Detect click outside some elements

  • A+
Category:Languages

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


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/

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: