0

I have created a nav and header section which both change color (along with the hero text) as the user scrolls down the page, link to fiddle below:

https://jsfiddle.net/mfen723/9swhejo5/35/

I need to select all three of the icon bars that I'm using using for the navbar toggler so they also change color along with the nav, hero background and text, but I can't seem to select all 3 icon bars.

I am currently using the function below but I understand that using document.querySelector selects only the first matching element

  const heroIconBarScroll = document.querySelector('.icon-bar.bar-top', '.icon-bar-bar-middle', '.icon.bar-bottom');

            window.addEventListener('scroll', () => {
                if (window.scrollY >= 46) {
                    heroIconBarScroll.classList.add('hero-icon-bar-scroll');
                } else if (window.scrollY < 56)
                    heroIconBarScroll.classList.remove('hero-icon-bar-scroll');
            });

I have tried using document.querySelectorAll but this seems not to select any of the icon bars.

Any advice appreciated.

Mark Fenwick
  • 147
  • 1
  • 2
  • 10

1 Answers1

5

Pass a single selector string that includes commas, instead of multiple arguments.

const els = document.querySelectorAll('.icon-bar.bar-top, .icon-bar.bar-middle, .icon-bar.bar-bottom');

To get all the matching elements rather than only the first, use document.querySelectorAll instead of document.querySelector.

Then, you will need to loop over the elements of the NodeList to manipulate each one.

els.forEach(el => el.classList.add('hero-icon-bar-scroll'));
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • I think I must have done this wrong as it seems still to be selecting the first element (.icon-bar.top-bar): 'const els = document.querySelectorAll('.icon-bar.bar-top, .icon-bar-bar-middle, .icon.bar-bottom'); window.addEventListener('scroll', () => { if (window.scrollY >= 46) { els.forEach(el => el.classList.add('hero-icon-bar-scroll')); } else if (window.scrollY < 56) els.forEach(el => el.classList.remove('hero-icon-bar-scroll')); }); – Mark Fenwick Jul 19 '23 at 12:50
  • 1
    @MarkFenwick You made a typo in the separate selectors. It should be: `const els = document.querySelectorAll('.icon-bar.bar-top, .icon-bar.bar-middle, .icon-bar.bar-bottom');` – Unmitigated Jul 19 '23 at 12:54
  • Typos amended `const els = document.querySelectorAll('.icon-bar.bar-top, .icon-bar.bar-middle, .icon-bar.bar-bottom');` though the class seems still only to be applied to the first element on scroll. – Mark Fenwick Jul 19 '23 at 13:06
  • 1
    @MarkFenwick I can't reproduce. Seems to work fine here: https://jsfiddle.net/gkcryfs4/ – Unmitigated Jul 19 '23 at 13:10
  • Found the issue at my side, it works perfectly as per the amended Fiddle. – Mark Fenwick Jul 19 '23 at 13:18