I’m trying to position an image to the top of the window, but having the scroll position calculated so the image which has position: fixed;
always stays on top and visible no matter if you’re scrolling or not. How can i do that? I want to use gsap to animate it to its position.
Here’s my current code:
html:
<img id="image" src="image.jpg">
JS:
function toggleState(event) {
if(event) {
const img = event.currentTarget;
const rect = img.getBoundingClientRect();
const st = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
const sl = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
const ct = document.documentElement.clientTop || document.body.clientTop || 0;
const cl = document.documentElement.clientLeft || document.body.clientLeft || 0;
const top = Math.round(rect.top + st - ct);
const left = Math.round(rect.left + sl - cl);
gsap.to(img, {
//what to do?
});
}
}
2
Answers
Doh. This is how you do it..
To position the image to the top of the window, but having the scroll position calculated so the image, which has position: fixed; always stays on top and visible no matter if you’re scrolling or not, and animate it to its position using gsap.