javascriptparallax

How do I make image stop at a certain point from a fixed location. (Example link provided)


I am trying to make this parallax effect where when you scroll down, the image follows to the next location, then stops at said location(or destination). Once it reaches its destination, I want it to stay there and as you continue to scroll down, The image cannot continue past the destination set on it and I want it to scroll off the window, not stick at the top. Although I feel like this would be a fairly basic parallax task, unfortunately I am new to parallax.

<div class="myimg">
    <img src="https://i.imgur.com/pzhXqfp.png" class="self" onclick="scrollWin()">
</div>
function scrollWin() {
    window.scrollTo(0,1);
}

on scrollTo, on the Y axis, I have tried 0, 1, 50, 100, 500, and all kinds of numbers, but even at the lower numbers, it will scroll the entire page.

Edit: I found a perfect example: https://www.apple.com/ph/shop/buy-ipad/ipad-mini .

I would like to replicate this exact thing with the iPad. It scrolls down to a certain point on the Y axis and once it hits its destination, it no longer moves down the page. I have also tried the following, which is something I found from another Stack Overflow question, but this one is sticking to to top, which is not exactly what I'm looking for. Close though!

$(window).scroll(function() {
    $(".myimg").css("top",Math.max(0,250-$(this).scrollTop()));
});

Solution

  • In the example website (https://www.apple.com/ph/shop/buy-ipad/ipad-mini) that you provided it is not a parallax effect but a sticky element in which it sticks to the screen at a given position until it reaches the end of its parent's height. To create this effect just write the following .html and .css code:

    body {
      padding-top: 50vh;
      padding-bottom: 200vh;
    }
    
    .parent {
      height: 100vh;
    }
    
    .sticky-box {
      background-color: blue;
      width: 500px;
      height: 500px;
      position: sticky;
      top: 0;
    }
    <div class="parent">
      <div class="sticky-box"></div>
    </div>

    We define a div element with position: sticky with top: 0 for it to stick in top of the screen. Notice: The sticky-box travels the full height of the parent in the fixed position (so we define height: 100vh in the parent). More information in https://developer.mozilla.org/en-US/docs/Web/CSS/position.