G
G
georgi19842021-06-09 12:38:39
JavaScript
georgi1984, 2021-06-09 12:38:39

How can I make the toggleClass dependent on page scrolling affect all classes, and not just the first one?

Hello, I have a toggle which depends on page scroll:

const link = document.querySelector('.header__link');

window.addEventListener('scroll', function(){
  link.classList.toggle('cactive', pageYOffset > 0);
});


But it only affects one .header__link , is it possible to have toggleClass affect all .header__link s?
querySelectorAll doesn't help

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Sokolov, 2021-06-09
@georgi1984

querySelector()returns only one, the first element found. And everything is necessary. This makes querySelectorAll()

const links = document.querySelectorAll('.header__link');

window.addEventListener('scroll', function(){
  links.forEach((el) => el.classList.toggle('cactive', pageYOffset > 0));
});

I
Igor Stasyuk, 2021-06-09
@HikariNoSekai

https://developer.mozilla.org/ru/docs/Web/API/Docu...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question