Synchronizing the scrolling of two elements with varying heights: A guide

There are two DIV elements in question: #page and #block :

<div id="page"></div>
<div id="block"></div>

The #block element has a fixed position and contains long content with the property overflow:hidden.

The #page element also contains some content, but its height may be longer or shorter than that of the #block element.

The goal is to achieve synchronized scrolling between these two elements. Something similar to this:

To synchronize the scroll between the header and footer elements of the #page and #block, we need to calculate the speed at which the #block element scrolls.

This is how I attempted to accomplish this:

  • Calculated the height of the #page element
  • Calculated the height of the content within the #block element (since it has a fixed height)
  • Calculated the scroll speed of the #block element using:

    $("#block").outerHeight / $("#page").outerHeight

  • Triggered the .scrollTop() of the #block element

Initially, it worked as intended, with the #block element scrolling faster than the #page element. However, towards the end, the #block element did not fully scroll.

Here is the JsFiddle link demonstrating the issue: http://jsfiddle.net/zur4ik/bQYrf/2/

If anyone can pinpoint what I might be doing wrong, I would greatly appreciate it. Thank you in advance.

Answer №1

It is important to consider the window height and subtract it from the heights of the elements.

$(window).scroll(function() {
    var pageH = $('#page').height() - $(this).height();
    var pageT = this.scrollY - $('#page').offset().top;

    $('#block').scrollTop(pageT / pageH * ($('#blockLength').height() - $(this).height()));
});

Check out the latest fiddle here: http://jsfiddle.net/bQYrf/4/

Answer №2

I came across two helpful resources on Stack Overflow that address this very question:

Based on my understanding of your question, this is the perfect solution for you: Synchronized scrolling using jQuery?

Another effective approach can be found here as well: How do I synchronize the scroll position of two divs?

Answer №3

function calculateViewportHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

var viewportHeight = calculateViewportHeight();

$(window).scroll(function() {

    var difference = ($("#containerSize").height() - viewportHeight) / ($("#mainContent").height() - viewportHeight);
    var positionToSet = $(window).scrollTop() * difference;

    $("#element").scrollTop(positionToSet);

    console.log("Updated scroll position");

});

http://example.com/code-example

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

Tips on modifying the style of a specific React component without affecting the others

In my attempt to modify a single style property of a specific React component upon clicking it, I encountered an issue where the changes applied to every instance of that component. Despite consulting the React tutorial and various sources for solutions, I ...

Iterate using jQuery through all child div elements

<div id="SelectedSection" class="selected"> <div class="sec_ch" name="7"> <div class="sec_ch" name="8"> <div class="sec_ch" name="9"> <div class="sec_ch" name="11"> <div class="clear"> </div> </di ...

Fetching information from the server in response to the data transmitted from the client

In need of help with sending a string id from the client to server side and retrieving related information using Node.js for the back-end. I have searched online but haven't found a solution yet. Hoping this isn't a redundant question. ...

The error message "Next.js 14 does not recognize res.status as a function"

I'm a newcomer to Next.js and I've been wrestling with an issue all day. Here's my API for checking in MongoDB if a user exists: import {connect} from '../../../../lib/mongodb'; import User from '../../../models/userModel&ap ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

Unable to use Office.context.mailbox.item.displayReplyAllForm with attachments on outlook.live.com as well as receiving internal server errors when using the Outlook API

When using office.js outlook add-ins, the displayReplyAllForm with attachments function is opening the reply form without attachments in outlook.live.com. However, it works perfectly fine in outlook.office.com. Is there any workaround for this issue? Off ...

Ways to prevent a background image from repeating in an HTML email without relying on CSS

I created a custom background picture, but when I tried to use it with CSS in Outlook, it didn't work. So, I added the picture directly into the body tag which allowed me to display it, but now it is repeating. Even after trying to prevent the repeti ...

Creating a personalized JavaScript clock based on a specific time

I have implemented a script below, and my goal is to customize the time displayed by the script and have it update automatically without requiring manual adjustment each time. (I want to set the time once and have the script manage the display) However, u ...

The iframe is not adjusting its size in relation to the parent window

For more information, click here: http://jsfiddle.net/5HYve/ <div style="position: fixed; top:0; right:0; width:300px; height: 100%; text-align:justify; overflow:hidden;" class="chat-container"> <iframe id="chat_1" style="width:300px;height:1 ...

Error in Express application due to uncaught SyntaxError

I am attempting to live stream data using websockets to Chartjs, however I keep encountering the following error. main.js:1 Uncaught SyntaxError: Unexpected token <https://i.sstatic.net/9OCI1.png https://i.sstatic.net/bmGeW.gif What could be causi ...

Node.js allows you to seamlessly upload multiple images from various form fields or input types simultaneously

<form action="/upload-images" method="post" enctype="multipart/form-data"> <input type="file" name="image1" /> <input type="file" name="image2" /> <input type= ...

Is there a solution for the continuous automatic incrementing of the jQuery UI spinner that occurs when I right-click on it?

Only Linux and Mac OS users are facing this particular issue, indicating a potential bug with the jQuery spinner. The bug also affects the spinner located at the following link: https://jqueryui.com/spinner/ <input class="spinner"/> $(".spinner"). ...

What is the fallback mechanism in Astro js when the cache is unavailable?

When the cache is not accessible in Next.js, the page will be server-side rendered and displayed using either the true or blocking fallback approach. I am curious about the approach taken by Astro.js in this situation. I am planning to develop a dynamic b ...

Difficulty rendering wireframe with Three.js MeshBasicMaterial

I am experiencing an issue with my geometry created using the three.js API. When I export an obj file from Blender and import it, the object renders faces instead of wireframe as desired. Could this problem be due to a mistake in my import or export proces ...

Understanding how events propagate in three.js

I am currently working on a scene that consists of multiple objects. To manipulate the selected object, I am using an orthographic camera controller. Specifically, I want to rotate the object with the mouse by pressing shiftKey + 1 (rotation around its own ...

Utilizing NPM packages within Grunt-powered workflows

When working with Node, the module loading system is quite straightforward using the require() method to load modules from various locations in the root folder. For example: var qr = require('qr-image'); However, I have been attempting to achi ...

Deciphering text using XQuery and <a> elements

Utilizing XQuery for extracting data from HTML pages has been quite an interesting challenge. The structure of the HTML body that I am working with looks something like this: <td> <a href ="hw1">xyz </a> Hello world 1 ...

What are the best techniques for styling a SELECT box with HTML and CSS?

I've received a form from a talented designer which includes SELECT inputs designed in a unique manner. Despite my attempts to add paddings, adjust backgrounds, I'm unable to replicate the exact appearance of the select box shown in the image. ...

Retrieving data from Google Places API in JSON format

Having some trouble with the Places API, I initially attempted to use $.ajax from jQuery but kept encountering an unexpected token error on the first element of the file. It turns out that JSONP cannot be fetched from the Places API. Below is a snippet of ...

Utilizing JavaScript, create a dynamic grid gallery with Div Spin and expand functionality

I am looking to create a unique effect where a div rotates onclick to reveal a grid gallery on the rear face. Starting this project feels overwhelming and I'm not sure where to begin. <ul class="container-fluid text-center row" id=" ...