<!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?
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')
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