Detect click outside div using javascript

后端 未结 7 1907
無奈伤痛
無奈伤痛 2020-12-02 13:10

I\'d like to detect a click inside or outside a div area. The tricky part is that the div will contain other elements and if one of the elements inside the div is clicked, i

7条回答
  •  感情败类
    2020-12-02 13:45

    You can check if the clicked Element is the div you want to check or not:

    document.getElementById('outer-container').onclick = function(e) {
      if(e.target != document.getElementById('content-area')) {
          console.log('You clicked outside');
      } else {
          console.log('You clicked inside');
      }
    }
    

    Referring to Here.

提交回复
热议问题