skip to Main Content

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


  1. Chosen as BEST ANSWER

    Doh. This is how you do it..

    const top = window.pageYOffset;
    const left = 0;
    
    gsap.to(img, {
      top: top,
      left: left,
      duration: 1,
      easing: "linear"
    });
    

  2. 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.

    <img id="image" src="image.jpg">
    
    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 = window.innerHeight - img.height;
        const left = sl + rect.left - cl;
    
        gsap.to(img, {
          top: top,
          left: left,
          duration: 1,
          easing: "linear"
        });
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search