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.

3
  • 2
    querySelector only returns one element. querySelectorAll returns potentially multiple Commented Sep 1, 2020 at 16:43
  • 2
    Does this answer your question? What do querySelectorAll and getElementsBy* methods return? Commented Sep 1, 2020 at 16:43
  • Thanks a lot for the link. This definitely helps to understand the principle behind this. Commented Sep 2, 2020 at 7:33

1 Answer 1

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");
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot of mate! Solved!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.