Search code examples
javascriptcssopacityfadeout

decrease the opacity js


I'm trying to decrease he opacity of an image while scrolling. It should be like fade out

var scrollPercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);

 if(scrollPercent < 0.25){
         var myImage3 = document.getElementById('wheat-image-main3');
         myImage3.style.opacity = '1'
     }
    
     if(scrollPercent > 0.25){
         var myImage3 = document.getElementById('wheat-image-main3');
         myImage3.style.opacity = '0'
     }

Solution

  • You just have to wrap it in a scroll event listener and it'll work:

    const myImage3 = document.getElementById('wheat-image-main3');
    
    document.addEventListener('scroll', (e) => {
        var scrollPercent = (document.body.scrollTop + document.documentElement.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight);
    
     if(scrollPercent < 0.25){
             myImage3.style.opacity = '1'
         }
        
         if(scrollPercent > 0.25){
             myImage3.style.opacity = '0'
         }
    })
    body {
      height: 200vh;
    }
    
    #wheat-image-main3 {
      transition: opacity 125ms ease-in-out;
      opacity: 1;
    }
    <img id="wheat-image-main3" src="//placehold.it/200/200" alt="">