Im trying to fade in a DIV using opacity when the user gets close to the bottom of the page. Let's say the page is 3000px high, i want the fade in to start at 2400px and end up completely faded in when the user hits the bottom.
Here is the function i use on the top, but i cant figure out the math i need to get the oposite effect on the bottom of the page...
useEffect(() => {
const handleScroll = event => {
const checkpoint = 500;
const start = 200;
let opacity;
const currentScroll = window.pageYOffset;
if (currentScroll >= start) {
if (currentScroll <= checkpoint) {
opacity = 1 - currentScroll / checkpoint;
} else {
opacity = 0;
}
} else {
opacity = 1 - currentScroll / checkpoint;
}
document.querySelector(".intro").style.opacity = opacity;
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
This is my try. But it does not work. In short. My theory is to map the difference between the checkpoint variable 2400 and the height variable 3000 to a value between 0.0 and 1. Then assign it to the opacity of the Div. But sadly my head cant figure it out.
useEffect(() => {
const handleScroll = event => {
let opacity;
const height = document.documentElement.scrollHeight - window.innerHeight
const checkpoint = height - 700;
const currentScroll = window.scrollY;
// if (currentScroll >= start) {
if (currentScroll <= checkpoint) {
opacity = 0
console.log('if opacity: ',opacity)
} else {
opacity = currentScroll / checkpoint * 1;
console.log('else opacity: ',opacity)
}
document.querySelector(".footer").style.opacity = opacity;
};
window.addEventListener('scroll', handleScroll);
return () => {
window.removeEventListener('scroll', handleScroll);
};
}, []);
Any help here would be greatly appreciated!
-R
CodePudding user response:
GSAP ScrollTrigger example.
ScrollTrigger.create({ trigger: document.body, start: "top top", end: "bottom bottom", // onCallback function });
CodePudding user response:
Please check this code
import React, { useEffect, useState } from "react";
export default function App() {
const [currentScroll, setCurrentScroll] = useState(0);
window.onscroll = function (e) {
// console.log(window.scrollY);
setCurrentScroll(window.scrollY);
};
useEffect(() => {
console.log(currentScroll);
},
[currentScroll]
);
return (
<div>
<h1>Hello World</h1>
.....
</div>
);
}