I am trying to move a div from left to right slowly as the user scrolls down. It should stay within it's section and doesn't have to move back to the left when you scroll up.
I am wondering how to do this without using any external package. This is what I have so far but the circle ends up scrolling off the page and I need it to stay on the right hand side once it has gotten there.
<div className="App">
<div className="sectionOne">
<div className="circle styles" style={{ position: 'absolute', left: `${position}rem` }}></div>
</div>
<div className="sectionTwo"></div>
</div>
const [position, setPosition] = useState('70')
function moveCircle() {
const speed = 5
const scrolltop = window.pageYOffset
const scrollAndSpeed = scrolltop / speed
console.log(scrollAndSpeed.toString())
setPosition(scrollAndSpeed.toString())
}
useEffect(() => {
window.addEventListener(
'scroll',
function () {
requestAnimationFrame(moveCircle)
},
false
)
}, [])
I just noticed that you are using rem for the positioning.
So the Math.min would not work for this scenario. You can use the css clamp function.
style={{ position: 'absolute', left: `clamp(0vw, ${position}rem, 100vw - 1rem)` }}
Note that the 1rem i have put in there, should be the width of the .circle element.