Home > Enterprise >  Dark/light mode with background scroll on change not behaving as intended
Dark/light mode with background scroll on change not behaving as intended

Time:01-15

I have built a a small project combining dark/light mode with a background scroll on change.

The scrolling change works with a nice transition as light mode.

But when I toggle to dark mode it does change, but you have to scroll a little for it to change. I want it to change immediately without scrolling.

I tried a few different ways using some examples from codepen for the scroll and went with this approach.

scroll logic

window.sections = [...document.querySelectorAll(".section")];

document.body.style.background = window.sections[0].getAttribute("data-bg");

window.addEventListener("scroll", onScroll);

function onScroll() {
  const section = window.sections
    .map((section) => {
      const el = section;
      const rect = el.getBoundingClientRect();
      return { el, rect };
    })
    .find((section) => section.rect.bottom >= window.innerHeight / 4);
  document.body.style.background = section.el.getAttribute("data-bg");
}

Then I built the dark light mode where you toggle dark mode and it changes the data-attributes to all grey.

toggle logic

const toggle = document.getElementById("toggle");
const sections = document.getElementsByClassName("section");

toggleHandler = () => {
  if (toggle.checked === false) {
    console.log("false");
    sections[0].setAttribute("data-bg", "#23b296");
    sections[1].setAttribute("data-bg", "#f15f61");
    sections[2].setAttribute("data-bg", "#DDBCF7");
    sections[3].setAttribute("data-bg", "#fca971");
  } if (toggle.checked === true) 
  {
    console.log("true");
    sections[0].setAttribute("data-bg", "grey");
    sections[1].setAttribute("data-bg", "grey");
    sections[2].setAttribute("data-bg", "grey");
    sections[3].setAttribute("data-bg", "grey");
  }
  console.log([...sections]);
  console.log(sections[0].dataset.bg);
};


toggle.addEventListener("click", toggleHandler);

Link to the repo

Link to deployed site

I'm a bit stuck really as to solve this issue. Any guidance would be appreciated.

CodePudding user response:

It looks like the issue is that the background color is only being updated on scroll, so when you toggle to dark mode the background color does not immediately change. One solution would be to call the onScroll function after updating the data-bg attributes in the toggleHandler. This will update the background color immediately after the toggle is clicked, rather than waiting for the user to scroll.

  • Related