Determine the vertical dimension of an element through a JavaScript event listener

I've been working on creating an Apple-style image sequence scroller from a codepen demo. Here's the link to the original: https://codepen.io/jasprit-singh/pen/LYxzQjB

My goal is to modify the JavaScript so that the scroll height is based on a parent div containing the canvas element. This way, I can have content above and below this section without triggering the scrolling behavior until it's in the viewport.

I believe the issue lies with the line

const html = document.documentElement;
as it's referencing the entire contents of the <html> tag instead of the specific parent div I want to target. However, I'm not sure how to make this change correctly.

I attempted replacing

const html = document.documentElement;
with
const html = document.getElementById("wrap1");
, but this adjustment caused everything to stop working without displaying any console errors.

What am I missing or what changes do I need to make to achieve the desired functionality?

Thank you for your help!

... (other HTML and JavaScript code blocks remain unchanged)

Answer №1

Considering my perspective, one approach is to include overflow-y: auto in the parent element's styling. Additionally, modifying the line

const html = document.documentElement;
to target the specific parent element (e.g.,
const html = document.getElementById("wrap1");
) as suggested. Subsequently, attaching a scroll listener to the parent by changing
window.addEventListener('scroll', () => {
to
html.addEventListener('scroll', () => {
. Following these adjustments, the image animation should respond to the parent's scrolling behavior, exemplified below:

const html = document.getElementById("wrap1");

const canvas = document.getElementById("hero-lightpass");
const context = canvas.getContext("2d");

const frameCount = 148;

const currentFrame = index =>
  (`https://www.apple.com/105/media/us/airpods-pro/2019/1299e2f5_9206_4470_b28e_08307a42f19b/anim/sequence/large/01-hero-lightpass/${index.toString().padStart(4, '0')}.jpg`);

const preloadImages = () => {
  for (let i = 1; i < frameCount; i++) {
    const img = new Image();
    img.src = currentFrame(i);
  }
};
const img = new Image();
img.src = currentFrame(1);

canvas.width = 1158;
canvas.height = 770;

img.onload = function() {
  context.drawImage(img, 0, 0);
};
const updateImage = index => {
  img.src = currentFrame(index);
  context.drawImage(img, 0, 0);
}

html.addEventListener('scroll', () => {
  const scrollTop = html.scrollTop;
  const maxScrollTop = html.scrollHeight - window.innerHeight;

  const scrollFraction = scrollTop / maxScrollTop;
  const frameIndex = Math.min(frameCount - 1, Math.ceil(scrollFraction * frameCount));

  requestAnimationFrame(() => updateImage(frameIndex + 1));
});
preloadImages();
#wrap1 {
  z-index: 1;
  margin: 0;
  padding: 0;
  background: #000;
  overflow-y: auto;
  max-height: 100vh;
}

#wrap {
  height: 500vh;
}

#wrap2 {
  position: relative;
}

canvas {
  position: absolute;
  max-width: 100%;
  max-height: 100vh;
  top: 50%;
  pointer-events: none;
  transform: translate(calc(-50% - 20px), -50%); /* add scrollbar width 20px so that it's visible */
  left: 50%;
}

body {
  margin: 0;
}
<div id="wrap2">
  <div class="wrap1" id="wrap1">
    <div class="wrap" id="wrap">
      <canvas id="hero-lightpass"></canvas>
    </div>
  </div>
</div>

Note: I made some alterations in the CSS code structure to resemble that of the provided snippet.

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

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

Customize Typography style variations in Material-UI version 5

I have encountered a similar issue, but with a twist from Can't override root styles of Typography from Materil-UI Back in v4, I had a theme set up like this: import { createTheme } from '@material-ui/core/styles'; export const theme = cre ...

Sending data to server with Backbone (using save() function and php script)

Wondering if you can assist me with an issue I'm facing. I am trying to utilize Backbone's save() method and send data to a php file. However, I encountered a problem right at the beginning. When I execute the following in the browser's co ...

Is there a way to send a variable to PHP and execute it on the current page?

I need to integrate an inventory search feature on a local clothing store's website. The challenge lies in setting up the PHP script that pulls and organizes the data to run on the same page as the search form itself. Given my limited experience with ...

Explain the concept of DOM components in relation to refs within the React JS framework

Before this issue came up in the React documentation for ref forwarding, there was a mention: The concept of ref forwarding doesn't just apply to DOM elements. It can also be used with class components. There's a discussion on another platform ...

Creating Radial Fades with CSS3

Seeking guidance on creating a background similar to the one shown here using just CSS. I believe it can be done, but I struggle with CSS3. The goal is for the background to be compatible with all modern browsers, not overly concerned about support for br ...

Unable to set a JSON data as a value for a JavaScript variable

I am currently developing a YT mp3 downloader using the API provided by youtubeinmp3. I have been successful in obtaining the download link in JSON format. https://i.stack.imgur.com/3mxF2.png To assign the value of "link" from the JSON to a JavaScript va ...

Excessive requests to location or history APIs in a brief period of time

Alert: Reached maximum update depth. This issue may arise when a component invokes setState within useEffect without a dependency array, or if any of the dependencies change on each render. const OwnerPage = () => { const onOpen = useAgencyModal((s ...

Error encountered: The Bootstrap Carousel function is causing a TypeError as e[g] is not defined

I am attempting to build a dynamic bootstrap carousel using my json data, and I have implemented jQuery-Template for rendering. Essentially, I am generating the carousel slider on-the-fly from my json data with the help of jQuery-Template. Here is a snippe ...

The drop-down menu is misaligned from its designated position underneath the title

Trying to incorporate a dropdown menu into my website, I am structuring the HTML as follows: <ul class="topnav"> <li> SECTION TITLE <ul class="subnav"> <li>One</li> <li>Two</li> ...

When attempting to open a link in a new tab, the ng-click function fails to execute

In Angular, utilizing both the <code>ng-click and ng-href directives at the same time will result in the click function being executed first. In this scenario, clicking on a link that navigates to Google will be prevented and instead an alert will be ...

Accessing Row Data from a Material Table using a Button Click, Not through Row Selection

My React component features a material table view, shown here: https://i.stack.imgur.com/OUVOD.png Whenever the delete icon is clicked in the table, I want to access the rowdata associated with that particular row. However, all I am able to retrieve is ...

Div with hidden scrollbars for smooth scrolling experience

Is there a way to create scrollable DIV's without visible scrollbars? While Mac OS 10.7-8 display no visible scrolls, other operating systems like Windows, Mac OS, and Linux show the scrollbars. How can I achieve scrollable divs without the scrollbars ...

What is the best way to deliver static HTML files in Nest.js?

I am encountering an issue with loading JS files from a static /dist folder located outside of my Nest project. While the index.html file loads successfully, any JS file results in a 404 error. In another Node/Express.js project, I am able to serve these ...

Here is a guide on determining the date variance in PHP by leveraging jQuery

I have been attempting to use the jQuery change function to calculate the variance between two dates, but I am encountering a problem as the code seems to be running smoothly without returning any results... <input type="text" name="datte1" class="form ...

Node.js is known for its unreliable promise returns

Currently, I have a function in place that establishes a connection with a sql database. After querying the database and formatting the results into an HTML table, the function returns the variable html: function getData() { return new Promise((resolv ...

Having trouble accessing information from Firebase Realtime Database within a React Native application

I am currently developing a React Native application that interacts with a Firebase database for reading and writing data. I have configured my Firebase permissions to allow read and write access: { "rules": { ".read": true, ...

A step-by-step guide on leveraging useRef() to specifically target dynamic material-ui tabs

When attempting to upload files to a specific channel, they always end up being uploaded to the first tab or channel. I've been using useRef to try and fix this issue, but I'm not sure what exactly is missing. By "tab," I am referring to the tab ...

Sending a function as a callback to children components in order to update a specific child component

I am currently working on developing a Navbar component that undergoes slight changes when a user logs in through a SignIn component. Here is an overview of how my application is structured: Initially, I have defined a state in the App component where aut ...

Experiencing a glitch with the Realtime Database feature on Firebase

// db.js file import * as firebase from "firebase/app" import "firebase/database" const config = { apiKey: "" ... } const db = firebase.initializeApp(config) export default db // App.vue ...