Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  99] [ 5]  / answers: 1 / hits: 22899  / 7 Years ago, fri, november 3, 2017, 12:00:00
<!DOCTYPE html>
<html>
<head>
<style>
.dropdown-content a{
display: block;
background-color: blue;
}
</style>
</head>
<body>
<div class=dropdown-content>
<a>1</a>
<a>2</a>
</div>
<script>
window.onclick = function(event){
if(!event.target.matches('.dropdown-content')){
alert(foo);
}
};
</script>
</body>
</html>


I'm trying to make alert(foo); execute only when we are NOT clicking on anything inside of the div tag in the body. Unfortunately, it executes no matter where I click. Why?


More From » jquery

 Answers
15



window.onclick = function(event){
if (document.getElementsByClassName('dropdown-content')[0].contains(event.target)){
// inside
} else{
// outside
alert('foo');
}
};

.dropdown-content a{
display: block;
background-color: blue;
}

<div class=dropdown-content>
<a>1</a>
<a>2</a>
</div>





Get your element and use contains to check whether click is in or outside. If outside then alert.



matches is not working because you are clicking in a tag which is not having .dropdown-content tag. So everytime value comes false. And it alert('foo')


[#56023] Wednesday, November 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
keyanah

Total Points: 642
Total Questions: 93
Total Answers: 114

Location: Virgin Islands (U.S.)
Member since Tue, Jul 7, 2020
4 Years ago
;