Search code examples
javascriptscrollcolorsbackgroundsections

Changing background color on scroll with javascript


https://codepen.io/tobiasthaden/pen/OVWKjm


$(window).scroll(function() {
  $('section').each(function(i) {
    if ($(this).position().top <= $(window).scrollTop()) {
      $('body').css('background-color', $(this).attr('data-color'));
    }
  });
});

Looking to replicate this effect using regular old javascript. I don’t want to use jQuery!

Any tips?


Solution

  • I would have done it like this.

    const sections = document.querySelectorAll('section')
    
    document.addEventListener('scroll', () => {
      sections.forEach(section => {
        if(section.getBoundingClientRect().top <= document.body.scrollTop) {
          document.body.style.background = section.dataset.color
        }    
      })
    })
    body {
      transition: background-color .2s ease;
    }
    
    section {
      height: 100vh;
    }
    <section data-color="white"></section>
    <section data-color="green"></section>
    <section data-color="purple"></section>
    <section data-color="yellow"></section>
    <section data-color="blue"></section>
    <section data-color="white"></section>