Search code examples
javascripthtmlcsslocomotive-scroll

Change Page Color On Scroll Using Locomotive Scroll


How to change Page color Smoothly on Scroll like this Amanda Braga Portfolio

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dpk</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/locomotive-scroll.min.css">

</head>

<body>

    <div data-scroll-container>
        <section data-scroll-section>
            <div class="container Blue"></div>
            <div class="container Red"></div>
            <div class="container Black"></div>
        </section>
    </div>

Here we can add Methods for changing Pagecolor

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/locomotive-scroll.min.js"></script>
    <script>
        const scroll = new LocomotiveScroll({
            el: document.querySelector('[data-scroll-container]'),
            smooth: true
        });
    </script>
</body>

</html>

Solution

  • Finally, I Found a Better way to achieve this

    Here is Code in case someone need

    HTML -

           <div class="vh-100">
                <span data-scroll data-scroll-repeat data-scroll-call="pageColor" 
                 data-scroll-id="blue"> ____________blue  </span>
           </div>
    
           <div class="vh-100">
                <span data-scroll data-scroll-repeat data-scroll-call="pageColor" 
                 data-scroll-id="green"> ____________green  </span>
           </div>
    
           <div class="vh-100">
                <span data-scroll data-scroll-repeat data-scroll-call="pageColor" 
                 data-scroll-id="#ff0000"> ____________red  </span>
           </div>
            
    

    CSS - (for Smooth Transitions)

    body{   
     transition: background-color 1s ease;
     }
     .vh-100{
       height:100vh;
      }
    

    JS - (GET ColorCode or Color name from data-scroll-id attribute from html element and assign it to body background color)

      setTimeout(() => {
        scroll.on('call', (value, way, obj) => {
    
          if (way === 'enter') {
            switch (value) {
              case "pageColor":
                // get color code from data-scroll-id  assigned to body by obj.id
                   document.querySelector('body').style.backgroundColor = obj.id;
                break;      
           }
          }
    
        });
      }, 800);