Update the image source every 20 pixels

I am trying to adjust the image source while scrolling down by 20 pixels, so that after 100 pixels the image source changes 5 times, with the initial src image being "falling-05.png". Despite following various tutorials, the implementation doesn't seem to be working as expected. Can anyone assist me in identifying the issue?

HTML

<div class="fixedContainer">
        <div class="scrollableContainer">
            <img class="character" id="character" src="./images/falling-01.png"/>
        </div>
</div>

<div class="anotherContainer"></div>

CSS

.fixedContainer {
position: relative;
width: 100%;
height: 100%;
background-color: red;
overflow-y: scroll;
}

.scrollableContainer {
position: relative;
width: 100%;
height: 1800px;
background: rgb(34,193,195);
background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1) 
100%);
}

.anotherContainer {
position: relative;
width: 100%;
height: 800px;
background-color: white;
display: ;
}

.character {
position: fixed;
right: 140px;
top: 150px;
}

JAVASCRIPT

var image = document.getElementById("character");
var sources = ["falling-01.png", "falling-02.png", "falling-03.png", "falling-04.png", "falling-05.png", "falling-06.png", "falling-07.png", "falling-08.png", "falling-09.png"];

var i = 0;
var breakpoint = 20;                           // Change to whatever you like

window.addEventListener("scroll", function() {
var scrollDown = document.body.scrollTop;
if (scrollDown >= breakpoint) {
   img.setAttribute(src, sources[i]);
   breakpoint += 20;                       //Change to whatever you like
   i++;
}
}

Answer №1

There is a mistake in the initial code:

var image = document.getElementById("character"); <-- declared as image
img.setAttribute(src, sources[i]); <-- referred to as img

Also, you are checking the scroll position on the body element

var scrollDown = document.body.scrollTop;

However, the scrollable part in your code is not the body component

.fixedContainer {
  ...
  overflow-y: scroll;
}

Answer №2

There seem to be a few errors in your code structure:

  • missing an closing parenthesis
  • img versus image
  • src should be used instead of 'src'
  • .anotherContainer has display: ;

Consider replacing document.body.scrollTop with window.pageYOffset to resolve the issue.

You may implement the following:

var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : 
(document.documentElement || document.body.parentNode || 
document.body).scrollTop;

Refer to Detecting by how much user has scrolled for more information.

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

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Can I create interactive stacked shapes with CSS and/or JavaScript?

Trying to explain this may be a challenge, so please bear with me. I need to create an "upvote" feature for a website. The number of upvotes is adjustable in the system settings. The upvote controls should resemble green chevrons pointing upwards. For exa ...

Bootstrap revamps dropdown menu code into a convoluted mess

I recently started working on a project with the Material Design theme from for a CodeIgniter application. However, I've encountered an issue with the dropdown functionality. It seems that Bootstrap is altering the original code, transforming it from ...

Highlighting Search Results in Kendo TreeView

I am currently working on a KendoTreeview project with spriteclass. My goal is to highlight both the root and child nodes with a specific search term. I have successfully implemented the search functionality, however, there is an issue that arises after th ...

Click on a new tab to enable printing options for the page

I am looking to enhance the print page functionality on my website. Currently, when the print icon in the footer is clicked, it opens the printer dialog box directly. I would like to change this behavior so that when the Print icon is clicked, the contents ...

"Applying CSS styles to HTML elements through PHP code

Hey there, I need help with some CSS styling for my PHP code. The code below is used to display a name: while ($db_field = mysql_fetch_assoc($result)) { print $db_field['ship_name'] . "<BR>"; I really want to jazz it up with some ...

Difficulty with Django's |safe template functionality

Issue with Django safe template functionality I attempted to utilize a textarea for rich text in the Django admin section, and everything seemed fine. However, when I try to display it on the front end using {{ date|safe }}, only a maximum height of appro ...

Impact of designs on the elements within components

Here's a CSS query I have: If I have the code below, does the styling apply to the contents of v-container but not v-container itself? <v-app id="inspire"> <v-container justify-center style="max-width: 1200px"> <v-layout row ...

The Ajax request functions correctly in Chrome and Safari but encounters issues in Firefox and Internet Explorer

I've encountered an issue with jQuery where the call is failing when making a request with base64 authorization header in the beforeSend function. It's a simple request to retrieve projects. function GetProjects(full){ var query = "/Projects"; $ ...

Using the filter() function in jQuery allows for efficient sorting and

My current area of study is in jQuery, but I'm encountering a bit of confusion with the following code: var list = mylist.filter(function(f) { return $(f) .find('.anthing') .length > 0; }); I'm particularly puzz ...

jqGrid: What could be causing the events I defined for grid edit to not fire?

I've been attempting to make in-line edits on a grid, but it seems like none of the events connected to those edits are being triggered. I am specifically looking to use afterSubmit: so that it triggers after the user has edited the Quantity field in ...

What is the best way to display all HTML content using PHP?

I have an HTML page with a multitude of CSS and JavaScript tags in its head section. My goal is to print them as they are on a PHP page. I've attempted using PHP echo file_get_contents("html_url"); and the fread function. The PHP page successfully loa ...

Automatically generated VueJS function

Creating a logging system for my Javascript Project using VueJS and Vuex To make logging methods accessible to all components, I am utilizing a global Mixin : import { mapState, mapActions } from 'vuex' import LogLevel from '@/enums/logger ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elem ...

Angular's import and export functions are essential features that allow modules

Currently, I am working on a complex Angular project that consists of multiple components. One specific scenario involves an exported `const` object in a .ts file which is then imported into two separate components. export const topology = { "topolo ...

What are some methods to prevent cookies from being overridden?

Just beginning my journey in web development. Currently utilizing asp.net Web API and Angular with token authentication. Every time a user logs in, I set the token in a cookie and send it with each request. Everything has been running smoothly so far, bu ...

Prevent cross-site scripting vulnerabilities by replacing the characters "'<'" and "'>'"

Is it possible to protect my website from XSS attacks by simply replacing < and > with &lt; and &gt;, or is there more to consider? For example: <?php echo '<div>' . $escaped . '</div>' ?> I am alread ...

Tips for Providing Real-Time Data for a Dynamic Chart in d3

I have a line chart sample from D3, and the issue I'm facing is that I need to continuously feed live data from a server at certain time intervals and use D3 to draw the chart based on this dynamic data. Despite my efforts to search for a solution, I ...