Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use event.target.matches to match div element

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

like image 649
Sahand Avatar asked Dec 18 '22 03:12

Sahand


1 Answers

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

like image 168
Durga Avatar answered Jan 02 '23 21:01

Durga