0

I want to check if one of this element is clicked:

<li id="myProjets" onclick="dropdown(this)">
   <img src="img/image.png">
   <span>Projets</span>
</li>

This is my code:

window.onclick = function (event) {
    if (event.target.matches('#myProjets')) {
        console.log('element clicked');
    }
}

When I click in the image or the span it doesn't work

nyaina
  • 21
  • 4
  • 1
    dropdown is not defined? – evolutionxbox Jul 19 '22 at 11:06
  • if you add a listener for the click event to the window element, you'll get click events occurring in the whole window of course so also when clicking on those child elements. But you have a condition to console.log that will be true only when the clicked element is the main div #myProjects. Plus you have errors in the code you shared (the onclick event defined in the html has no corresponding function in js) – Diego D Jul 19 '22 at 11:06
  • In fact I want to check if my element isn't clicked. The test is: if (!event.target.matches('#myProjets')) { console.log('outside element clicked') } – nyaina Jul 19 '22 at 11:14

1 Answers1

1

You have a problem with the way you select the element. Moreover, you should avoid onXXX events with HTML if you are not using React or something similar

let element = document.querySelector('#myProjects')
element.addEventListener("click", ()=>console.log('element clicked'))
<li id="myProjects">
   <span>Projets</span>
</li>

And with the added constraint to click outside

document.addEventListener('click', e => {
  if (document.getElementById('myProjects').contains(e.target)) {
    console.log('Im clicked')
  } else {
    console.log('Im not clicked')
  }
})
<li id="myProjects">
   <span>Projets</span>
</li>
JeanJacquesGourdin
  • 1,496
  • 5
  • 25