Home > OS >  can't add event listeners to elements using querySelectorAll()
can't add event listeners to elements using querySelectorAll()

Time:01-19

I'm trying to add a mouseover event on some links with the data-hide-links attribute, but it's not working at all.

I know that my loop is working fine and that it selects the right elements because I can console.log() the elements that I want. I also know for sure that the event listener is not adding to the element because when I look at the prototype of the elements the onmouseover property is null

Here's the code:

let hideLinks = document.querySelectorAll("[data-hide-cursor]");
for (let i = 0; i < hideLinks.length; i  ) {
  hideLinks[i].addEventListener("mouseover", () => {
    document.getElementById("cursor").classList.add("hide");
  });
}
#cursor {
  top: 0;
  left: 0;
  border-radius: 50%;
  pointer-events: none;
  z-index: 1000;
}

#cursor>div {
  border-radius: 50%;
  width: 1.25rem;
  height: 1.25rem;
  background: black;
  transition: transform 0.5s ease, opacity 0.35s ease;
}
<div id="cursor" data-cursor>
  <div></div>
</div>
<button data-hide-cursor type="submit" >
  Submit
</button>

I tried to deconstruct the elements into an array using let [...hideLinks] = ... but it did not change a thing.

CodePudding user response:

Your code works fine. Class hide just doesn't do anything

let hideLinks = document.querySelectorAll("[data-hide-cursor]");
for (let i = 0; i < hideLinks.length; i  ) {
  hideLinks[i].addEventListener("mouseover", () => {
    document.getElementById("cursor").classList.add("hide");
  });
}
#cursor {
  top: 0;
  left: 0;
  border-radius: 50%;
  pointer-events: none;
  z-index: 1000;
}

#cursor>div {
  border-radius: 50%;
  width: 1.25rem;
  height: 1.25rem;
  background: black;
  transition: transform 0.5s ease, opacity 0.35s ease;
}

#cursor.hide {
  background: red;
}
<div id="cursor" data-cursor>
  <div></div>
</div>
<button data-hide-cursor type="submit" >
  Submit
</button>

  • Related