I am currently working on a project where I want to create an effect that moves an image from the top of the document to the bottom based on the scroll percentage. When the site is loaded, the image will start at the top and gradually move down as the user scrolls, ultimately reaching the bottom at 100% scroll progress.
I have researched various solutions on stackoverflow and other websites, but only found two that are somewhat close to what I need.
The first solution works, but it is limited to a specific resolution which needs manual adjustment in the code:
var imgscroll = document.getElementById('myimg');
window.addEventListener('scroll', function() {
var scrollposition = window.scrollY;
imgscroll.style.top = scrollposition * 0.1323 + 'vh';
}
The second solution comes from a stackoverflow answer - found here and provided below - Although I believe the percentage aspect is what I require, I couldn't get it to work (the image stopped moving):
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 occurs.
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';
});
I would greatly appreciate any guidance or suggestions on how I can achieve the desired outcome.