decrease the opacity js

72 Views Asked by At

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'
     }
3

There are 3 best solutions below

0
Jonas Grumann On BEST ANSWER

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="">

0
Edmon Belchev On

You need to add scroll event listener.

addEventListener("scroll", (event) => {
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'
     }
})
0
vbaguet On

You have to listen the scroll events to get this work. Below is an example, but you can achieve this working with CSS class as well and classList property.

const img = document.querySelector('.image')

document.addEventListener('scroll', (e) => {
    if(this.scrollY >= 100) {
        img.style.opacity = "0.5"
    }
    else {
        img.style.opacity = "1"
    }
})
<img src="" height="500" class="image" />