0

I've created the following lines of code to animate the gradient of the blue buttons (https://konzerthofner.webflow.io/events/2-11-im-11-der-auftakt-2020). Everything works as expected, until I decide to use more than one button of this kind. In this case only the first button gets animated. I think the problem is, that I'm always selecting the first element inside the DOM with the corresponding class. Unfortunately I'm not able to provide a working solution for this.

My JS to change one button:

var cta = document.querySelector('.khctaglobal');
cta.addEventListener("mousemove", (e) => {
  console.log("mousemove success");
    let rect = e.target.getBoundingClientRect();
  let x = e.clientX - rect.left;
  cta.style.setProperty('--x', x + "px");
});

My failed attempt to solve this problem:

var cta = document.querySelector('.khctaglobal');
cta.addEventListener("mousemove", (e) => {
  console.log("mousemove success");
    let rect = e.target.getBoundingClientRect();
  let x = e.clientX - rect.left;
  cta.forEach(el => el.style.setProperty('--x', x + "px"));
});

Thanks a lot for your help.

Atheneor
  • 51
  • 9
  • 2
    `querySelector` only returns one element. `querySelectorAll` returns potentially multiple – Taplar Sep 01 '20 at 16:43
  • 2
    Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – Taplar Sep 01 '20 at 16:43
  • Thanks a lot for the link. This definitely helps to understand the principle behind this. – Atheneor Sep 02 '20 at 07:33

1 Answers1

2

Use querySelectorAll to grab the entire list of elements by that selector (class).

document.querySelectorAll('.khctaglobal').forEach(cta => ...);

You can conveniently call NodeList.prototype.forEach to loop over the selected elements.

Example

document.querySelectorAll('.khctaglobal').forEach(cta => {
  cta.addEventListener("mousemove", (e) => {
    console.log("mousemove success");
    let rect = e.target.getBoundingClientRect();
    let x = e.clientX - rect.left;
    cta.style.setProperty('--x', x + "px");
  });
});
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132