Home > Blockchain >  Is there a way to make a button fade as you scroll down the page?
Is there a way to make a button fade as you scroll down the page?

Time:08-27

I have a bouncing down arrow at the bottom of the screen of my website (the button part isn't completed yet, but the visual part is there) that stays in the same spot when you scroll down the page.

This is the code for the button:

@keyframes bouncing {
    0% {bottom: 0;}
    50% {bottom: 10px;}
    100% {bottom: 0;}
}

.arrow {
    animation: bouncing 1s infinite ease-in-out;
    bottom: 0;
    display: block;
    height: 50px;
    left: 50%;
    position: absolute;
    width: 50px;
}
<div>
    <img  src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_down_48px-128.png"/>
</div>

Is there a way to make the arrow fade out when you scroll down the page in JS or CSS?

thanks

CodePudding user response:

You can listen to window.onscroll to listen which offset position you are when there is an scroll event. here is a solution for hiding you image when scrolled to down with javascript:

var prevScrollpos = window.pageYOffset;
window.onscroll = function () {
  console.log("scrolled");
  var currentScrollPos = window.pageYOffset;
  if (prevScrollpos >= currentScrollPos) {
    console.log(prevScrollpos, currentScrollPos);
    document.getElementById("arrow").style.display = "block";
  } else {
    console.log(prevScrollpos, currentScrollPos);
    document.getElementById("arrow").style.display = "none";
  }
};

note: You need to add an id with value of arrow to your image tag. also here is the link for sample code.

CodePudding user response:

To add to @Mahdi-Jafaree's answer, which is fine but only 'hides' and 'shows' the arrow instead of fading it, I tweaked the code a bit.

let opacityPercentage = 100;

document.addEventListener('DOMContentLoaded', () => {
  const arrowElement = document.getElementById('arrow');
  
  window.onscroll = () => {
    opacityPercentage = Math.max(100 - window.pageYOffset, 0);
    arrowElement.style.opacity = opacityPercentage / 100;
  }
});
@keyframes bouncing {
    0% {bottom: 0;}
    50% {bottom: 10px;}
    100% {bottom: 0;}
}

.arrow {
    animation: bouncing 1s infinite ease-in-out;
    bottom: 0;
    display: block;
    height: 50px;
    left: 50%;
    position: absolute;
    width: 50px;
}
<div style="height: 200vh;"> 
  <div>
      <img  id="arrow" src="https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_down_48px-128.png"/>
  </div>
</div>

  • Related