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

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...

Leveraging jest for handling glob imports in files

My setup involves using webpack along with the webpack-import-glob-loader to import files utilizing a glob pattern. In one of my files (src/store/resources/module.ts), I have the following line: import '../../modules/resources/providers/**/*.resource. ...

Send a property as a string, then transform the string back into JavaScript

I am in the process of creating a versatile carousel that will cater to various conditions. Therefore, I need to set the "imageQuery" on my display page as a string and then make it work as executable javascript within my carousel. The query functions pr ...

Guide to creating 2D point shapes with three.js

Is there a way to render a 2D shape of points in three.js? I have been struggling to find a working geometry for this task. I simply want to create a polygon of points that lie on the same plane. The 'Shape' object doesn't seem to be suitab ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Is there a way to differentiate between a preflight request and the actual request?

Currently, I am utilizing CORS to transmit data to a server located on a different domain. Initially, the browser dispatches the preflight request to verify the server, followed by the main request. My goal is to identify when the request is in the "prefl ...

Preventing button movement during navigation collapse toggle click

I am working on setting up my navbar in the following way: [collapse] navbar icon links sign in button Although I have successfully set this up, the issue is that when the navbar collapse toggle is clicked, it shifts the sign-in button u ...

ways to update ng-model once it has been validated

When using ng-model for input, I want to maintain the original value if an invalid number is entered. How can I accomplish this? For reference, visit the Plunker at: http://plnkr.co/edit/wX7n0jBn1Ek1py4DJHqT?p=preview The input box utilizes ng-model for b ...

The placeholder string is being accepted as the input value for the number

My issue is with a form input of type number. When the form is submitted without entering any number, it treats the placeholder text "rating" as the value. How can I stop this from happening? I need to make sure that the input number field is marked as in ...

What is causing the border-radius property to malfunction on a particular website when using Internet Explorer?

We create browser add-ons for popular browsers like Google Chrome, Firefox, Safari, and Internet Explorer. Our add-ons inject HTML elements into various websites such as mail.google.com and email14.secureserver.net. The HTML element we use has a border-ra ...

Outside drop shadows in CSS3 creates an interesting visual effect by giving

I am currently using the following CSS styling for a list of li items. border: 1px solid black; border-radius:10px; box-shadow: 8px 8px 4px #666; -o-box-shadow: 10px 10px 5px #888; -icab-box-shadow: 10px 10px 5px #888; -khtml-box-shadow: 10px 10px 5px #8 ...

Image set as the background on a website

I recently started working with Groovy and Grails, designing my own personal website. I'm looking to set an image (located in the asset folder) as the background for my index.gsp page. How can I achieve this? ...

Use jQuery to set a Firebase image as the background of a div element

Is there a way to fetch an image from Firebase and use it as the background for a div element? I've tried several approaches without success. Could someone share some examples on how to achieve this? <div class="museBGSize rounded-corners grpelem" ...

Guide to parsing JSONP information using Express

I am attempting to transfer data from phonegap to an express application. Below is the code I am using: Phonegap: $.ajax({ type: 'POST', url:"http://127.0.0.1:3000/test", data: {"test":"this works!"}, dataTyp ...

When switching windows or tabs, the user interface of the browser extension vanishes

As someone who is new to web application development and browser extension creation, I have encountered a challenge with my browser extension. When the extension popup is open and I switch browser windows, the UI (popup.html) disappears. It reappears whe ...

Using R programming language to download PDF files from a website through web scraping

Looking for assistance in R coding to automatically download all the PDFs linked on this URL: . The goal is to save these PDFs into a designated folder. I've attempted the following script with guidance from , however, it's resulting in errors: l ...

"Autodesk Viewer: Unlocking the Power of Programmatic Camera Y-Axis Reversal

I have been utilizing the markups core extension to retrieve and restore the viewer state, which has been successful, except for a problem with inversion (only in 3D). When a client interacts with the y-axis specifically, causing the model to flip to revea ...

Guide on adjusting the size of an image based on either its width or height dimensions

Currently, I am retrieving product images from an API but unfortunately, they do not have consistent dimensions. My goal is to display these images within a 250x250 div. In some cases, the image is in portrait orientation and should be scaled based on its ...

Creating an HTML table by populating it with data from a JavaScript array

Imagine you have a JavaScript array structured like this: [ "Heading 1", "Heading 2", "Data 1", "Data 2", "Data 3", "Data 4", ] Your task is to generate an HTML table from this array that looks like the one in this link: https://i.stack.imgur.com/7laUR. ...

Troubleshooting issue with node.js 13 import functionality

$ node --version v13.8.0 We will now proceed to create three files: // package.json { "type": "module" } // foobar.js function foo() { console.log('foo') } export default {foo} // index.js import Foo from './foobar ...