How do I make an image move when i scroll down?

18,565

var container = document.getElementById('container');
var windowHeight = window.innerHeight;
var windowWidth = window.innerWidth;
var scrollArea = 1000 - windowHeight;
var square1 = document.getElementsByClassName('square')[0];
var square2 = document.getElementsByClassName('square')[1];

// update position of square 1 and square 2 when scroll event fires.
window.addEventListener('scroll', function() {
  var scrollTop = window.pageYOffset || window.scrollTop;
  var scrollPercent = scrollTop/scrollArea || 0;

  square1.style.left = scrollPercent*window.innerWidth + 'px';
  square2.style.left = 800 - scrollPercent*window.innerWidth*0.6 + 'px';
});
body {
  overflow-x: hidden;
}

.container {
  width: 100%;
  height: 1000px;
}

.square {
  position: absolute;
}

.square-1 {
  width: 100px;
  height: 100px;
  background: red;
  top: 600px;
}

.square-2 {
  width: 120px;
  height: 120px;
  background: black;
  left: 800px;
  top: 800px;
}
<div class="container" id="container">
  <div class="square square-1"></div>
  <div class="square square-2"></div>
</div>

Hope to help you.

Here you can see more examples about movable elements and scroll events.

Share:
18,565
Mario
Author by

Mario

Adobe Commerce / Magento / Front-end Developer

Updated on June 14, 2022

Comments

  • Mario
    Mario almost 2 years

    Here is an example of what i want to achieve: https://www.flambette.com/en/

    I have tried to change the css properties of images but that effect does not satisfy my needs. I have tried the following code:

    mydocument.on('scroll',function() {
          if (mydocument.scrollTop() > 10 && mydocument.scrollTop() < 200 ) {
             $('#first').css('top', '320px');
             $('#first').css('left', '215px');
             $('#first').css('transition', '0.5s');
          } 
          else {
             $('#first').css('top', '300px');
             $('#first').css('left', '200px');
             $('#first').css('transition', '0.5s');
          }
    }); 
    

    This is supposed to move an image when you scroll between 10 and 200 px.

    • Stuart
      Stuart over 6 years
    • Ivan
      Ivan over 6 years
      @Stuart are you sure it's the right link?
    • Stuart
      Stuart over 6 years
    • Mario
      Mario over 6 years
      I understand your confusion. Sorry for not making myself clear... What I'm trying to do is achieve this effect: jsfiddle.net/MMZ2h/4 And i want to apply this effect here: marioagaj.esy.es/transition I just don't know how to mix them together, that's all. Thanks in advance!