Search code examples
javascriptjqueryscrollpixel

Show div when it is 20% away from the bottom of the screen


Heyo,

so I was wondering if it is possible to show the fade-effect of a div, if it is 20% away from the bottom within the currend screen view. So for example if you scroll down on a page and the following contentbox gets a distance of 20% of the screen-height to the bottom of the screen, the fade-in effect runs.

I want this because of the responsive function. I don't want to write a new pixel height for the fade-effect everytime the Screensize changes.

Here's the code I'm currently using:

function Scroll(){
var top = document.getElementById('div1');
var ypos = window.pageYOffset;
    if (ypos > 1000){
        top.style.opacity = "1";
    }
    else {
        top.style.opacity = "0";
    }
}
window.addEventListener("scroll",Scroll);

Solution

  • Have you looked into scroll combined with position and height? https://api.jquery.com/scroll/ and https://api.jquery.com/position/ On the scroll you could get the position of the element in question and compare to the window. http://api.jquery.com/height/ and How to get the 'height' of the screen using jquery Those should be all the tools you need.