Atheneor
Atheneor

Reputation: 51

JS: How to change the style of multiple Elements with the same class

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.

Upvotes: 0

Views: 395

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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");
  });
});

Upvotes: 2

Related Questions