Home > Net >  Adding Scroll Transition using Javascript
Adding Scroll Transition using Javascript

Time:11-27

I am using javascript to hide an image after one scroll. The code is working fine but I am unable to add any transition to it due to which there is a very choppy and rough feel.

This is the code which I am using


function runOnScroll() {
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
      document.getElementById("logoimg-hidden").style.maxWidth = "0";    
       document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
      }
  else{
     document.getElementById("logoimg-hidden").style.maxWidth = "inherit";
    document.getElementById("logoimg-hidden").style.transition = "max-width .4s linear"
  }
 }; 
window.addEventListener("scroll", runOnScroll);

The transition doesn't work. I would be really thankful if I can get a solution to add transition as well on scroll. Thanks!

CodePudding user response:

Try setting the transition property through CSS rather than through JS.

#logoimg-hidden {
    .
    .
    .
    transition: max-width 0.4s linear;
}

CodePudding user response:

Using inherit for max-width seems to be the issue. Try giving it a value with a measurement unit like px, %, etc.

function runOnScroll() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
      document.getElementById("logoimg-hidden").style.maxWidth = "0";    
  } else{
     document.getElementById("logoimg-hidden").style.maxWidth = "100%";
  }
}
window.addEventListener("scroll", runOnScroll);
div {
  height: 400vh;
}

#logoimg-hidden {
  padding: 20px;
  background-color: #555;
  transition: max-width .4s linear;
}
<div>
  <div id="logoimg-hidden">image</div>
</div>

  • Related