Adjust the position of the image on the webpage to move vertically across the screen based on the


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.

Answer №1

One of the most innovative scripts I've come across on the web is the method of controlling image position using animation-play-state: paused and assigning a CSS variable to the animation-delay. You can check out the original pen by Chris Coyier here. Here's a quote from his website explaining this technique:

A positive animation delay means the animation waits for a certain amount of time before starting, while a negative animation delay starts the animation immediately as if that time has already passed. In other words, it allows you to start the animation at a point further into the cycle.

Upon window load, we calculate the space available below the image and the overflow on the page. A CSS variable --maximum defines the end point of the animation, which recalibrates when the user resizes the screen. While scrolling, another CSS variable --epoch manages the timing of the keyframe animation based on the progress ratio set.

let aim = document.getElementById('image'), room, overflow;

window.addEventListener('load', setEdge);
window.addEventListener('resize', setEdge);

window.addEventListener('scroll', function() {

  let ratio = (this.pageYOffset || this.scrollY)/overflow;

  aim.style.setProperty('--epoch', ratio);
});

function setEdge() {

  room = window.innerHeight;
  overflow = document.body.scrollHeight-room;

  aim.style.setProperty('--maximum', room-aim.height + 'px');
}
body {
  margin: 0;
  height: 700vh;
}

#image {
position: fixed;
animation-duration: 1s;
animation-timing-function: linear;
animation-play-state: paused;
animation-iteration-count: 1;
animation-fill-mode: both;
animation-name: move;
animation-delay: calc(var(--epoch) * -1s);
}

@-webkit-keyframes move {

0% {
 transform: translateY(0);
}
100% {
 transform: translateY(var(--maximum));
}
}

@keyframes move {

0% {
 transform: translateY(0);
}
100% {
 transform: translateY(var(--maximum));
}
}
<img id="image" src="https://via.placeholder.com/140x100" alt="">

If you want to experiment with this script, feel free to visit this link.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I use jQuery to set up form validation for an input textfield?

Check out this code snippet: <form data-test="loginForm-container" novalidate="" method="POST" enctype="multipart/form-data"> <div class="css-o5d3v1 e1ovefus2"> <div data-test="guestForm-email-wrapper" class="e1ovefus1 css-yjv4po e1eu3s ...

Utilizing AngularJS to create an auto complete feature integrated with a SQL Server database

I have a SQL database table with columns as follows: Row1 Row2 Row3 Id Country 1 1a 1b 34 Europe 2 2a 2b 45 US 3 3a 4d 5g Australia I am currently working on implementing an autocomplete feature ...

Error: Unable to set attribute because the property is undefined in the onLoad function

Can anyone help troubleshoot this error? List of included files: <link rel="stylesheet" href="../../node_modules/semantic-ui/dist/semantic.min.css"> <link rel="stylesheet" href="../../node_modules/font-awesome/css/font-awesome.min.css"> <l ...

Using traditional JavaScript, bring in a class from Node.js

I have a mix of files utilizing the Node.js framework and others that I'd like to incorporate without it. When attempting to import a class from my Node files, where module.exports was used, into my JavaScript files, I encounter an error stating "the ...

Personalize the hover effect and underline style of links in material-ui

I am currently delving into the world of material-ui custom styles and came across this helpful resource. However, I find myself a bit lost in how to properly override the classes using withStyles. <Breadcrumbs aria-label="breadcrumb" separator=" ...

Is it true that loading "undefined" into an array can use up a significant amount of memory?

I've encountered a strange issue where a bug is consuming excessive memory and leading to frequent server crashes. Every 30 seconds, a value is saved to an array: historicalValues.push( valueToSave ) When valueToSave is set to 1, the memory usage r ...

Hiding fields based on radio button selection in Prestashop checkout using jQuery

Currently, I have 2 radio buttons and several fields on my checkout page. This is what I want to achieve: - When the "delivery to address" radio button is selected, I want to display fields for address1, postcode, and city while hiding the id_state field. ...

The transcription generated by the Google speech-to-text service came back blank when processing the audio captured by the MediaRecorder API within

I am currently working on a project involving transcribing speech into text and I am utilizing the Google Speech to Text API with Next.js/React. I'm recording audio using the MediaRecorder API of a web browser. Interestingly, when I use the audio reco ...

Design a button for removing the selected value in select2

Can anyone provide some guidance on using select2? I am working with 2 select2 elements, and I want the selected value to be displayed on a button instead of in the input area of the select2. This way, the select2 will still display the placeholder text. ...

Struggling with updating the header in React Navigation?

Having trouble updating the screen header in my react native application when navigating to the Dashboard Screen after login. I've tried different methods but can't seem to figure out what's wrong. After logging in, I navigate to the Dashbo ...

I'm having trouble getting the npm install for classnames to work within my li tag

I need some help with React JS. I'm attempting to merge my classes using the npm package called classnames. https://www.npmjs.com/package/classnames However, I'm encountering an issue: classnames doesn't seem to be working as expecte ...

Div being visually overtaken by background image

I am struggling to make the image declared in bg fit into the container-fluid without overflowing. You can check out the live example at . The main objective is to position the text on top of the image so that I can apply opacity and blur effects to the i ...

What is the best way to organize components in ReactJS?

Confusion I am seeking clarification on the placement of my aside code. It is meant to render components such as searchInput and menuStudy. I was considering placing it in the container's folder, but it does not serve any specific purpose like hand ...

Loading and Manipulating OBJ Models with THREE.js

I am experiencing an issue with accessing an object outside of the event boundaries. When I put the object in an array and check out that array, it appears to be empty; however, within the event scope, it is full. I am seeking a solution for how to acces ...

Rotate the image as you hover your cursor over it

I am trying to implement a script where the image is rotated when the user hovers over it. Unfortunately, the hovering effect is not functioning as expected. $("#alcazar-image").rotate({ bind: { mouseover : function() { $(this).rotate({anima ...

What is the computational efficiency of accessing the size property of a Map in JavaScript?

I'm curious about the time complexity of this method compared to using .length on an array. Check out this link for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size ...

Retrieving JavaScript values using Selenium

I am trying to retrieve these JavaScript values from a web application. var contestPlayResponse = { "winningPrizeIndex" : 1, "playMode" : "NORMAL", "playerId" : "abc123", "gameVersion" : "0-1-86", "gameId" : "blue250k ...

Can markdown generated HTML be bound to an Angular 4 component?

I'm currently using Angular 4 to develop an app similar to a wiki, allowing users to create their own pages and link them using a markdown text editor controlled by a component/directive. That's the goal, at least. For example: The custom markd ...

Input Error in ASP.NET JavaScript

Within my ASP.NET website, I have implemented an <asp:TextBox /> where the text input is encoded using HttpUtility.HtmlEncode(); Furthermore, the page is equipped with validation controls like <asp:RequiredFieldValidator /> and <asp:CustomV ...

Different ways to create audio using GWT

Looking for ways to incorporate audio into your GWT app? I am considering creating a simple game, but it seems like there hasn't been much progress on direct audio support within GWT. This is likely due to the lack of underlying browser support, but I ...