westerschouwen strand

Change background color on scroll...

For a site that has a header with a transparent background (necessary for an effect I need to create), I ran into the problem that scrolling caused the text to move right through the logo.

So I was looking for a way to change the header background on scroll. That requires Javascript, and I don't speak Javascript, although I can usually figure out what it's doing. Not easy to find. Found a lot of solutions that used jQuery, but J!4 no longer comes with jQuery, so I needed a vanilla JS solution.

I was about to give up, and then I found this:  How to remove class on scroll top and add on scroll down on html body using JavaScript.
That looked as if it might do the trick, and of course there's only one way to find out: experiment. Nope. That's not doing what I hoped it would do.

Then I found this: Vanilla JW: change class on scroll on Github. Oh my! That does more or less exactly what I'm looking for, but it adds the class to the same div it's watching to determine the "add class" point. But in my case, I need to add the class to body (preferably) based on watching the banner...
That can't be very difficult (I think), but I'm not sure I can change that by myself...

I made a custom module with the following JS:

  let scrollpos = window.scrollY
  const header = document.querySelector("header")
  const header_height = header.offsetHeight

  const add_class_on_scroll = () => header.classList.add("fade-in")
  const remove_class_on_scroll = () => header.classList.remove("fade-in")

  window.addEventListener('scroll', function() { 
    scrollpos = window.scrollY;

    if (scrollpos >= header_height) { add_class_on_scroll() }
    else { remove_class_on_scroll() }