Trigger the scrolling of one div when another div is scrolled

Link to Jsfiddle

I'm attempting to activate my current scroll while I am outside that scroll, specifically in #DivDet

Here is the code snippet of what I have tried so far:

$("div#DivDet").scroll(function () {
    // Still trying to figure out what should go here      
    // Maybe something like $("div#scrlDiv").scroll();
});

Answer №1

If you're looking to synchronize the scroll of one div with another, it can be achieved by handling the scroll event.

To control the scrolling behavior of a specific element (the target div), you can utilize the properties scrollTop and scrollLeft, both measured in pixels. To ensure two divs scroll together seamlessly, simply set the source div's scrollTop and scrollLeft values to match those of the target div.

For example: Live Example | Source Code

Here is the relevant JavaScript code snippet:

(function() {
  var target = $("#target");
  $("#source").scroll(function() {
    target.prop("scrollTop", this.scrollTop)
          .prop("scrollLeft", this.scrollLeft);
  });
})();

Alternatively, you can retrieve the raw HTML element like so (source code):

(function() {
  var target = $("#target")[0]; // <== Getting raw element
  $("#source").scroll(function() {
    target.scrollTop = this.scrollTop;
    target.scrollLeft = this.scrollLeft;
  });
})();

This is how the full page structure looks:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<meta charset=utf-8 />
<title>Scrolling Demo</title>
  <style>
    .scroll-demo {
      display: inline-block;
      width: 40%;
      border: 1px solid black;
      margin-right: 20px;
      height: 100px;
      overflow: scroll;
    }
  </style>
</head>
<body>
  <p>Adjust the left div's scroll and observe the synchronization on the right.</p>
  <div id="source" class="scroll-demo">
    1
    <br>2
    <br>3
    <br>4
    <br>5
    <br>6
    <br>7
    <br>8
    <br>9
    <br>10
    <br>11
    <br>12
    <br>13
    <br>14
    <br>15
    <br>16
    <br>17
    <br>18
    <br>19
    <br>20
  </div>
  <div id="target" class="scroll-demo">
    1
    <br>2
    <br>3
    <br>4
    <br>5
    <br>6
    <br>7
    <br>8
    <br>9
    <br>10
    <br>11
    <br>12
    <br>13
    <br>14
    <br>15
    <br>16
    <br>17
    <br>18
    <br>19
    <br>20
  </div>
  <script>
  (function() {
    var target = $("#target");
    $("#source").scroll(function() {
      target.prop("scrollTop", this.scrollTop)
            .prop("scrollLeft", this.scrollLeft);
    });
  })();
  </script>
</body>
</html>

Answer №2

Method using Pure JavaScript

function synchronizeScrolling(elem1, elem2) {
  elem1.onscroll = function() {
    elem2.scrollTop = this.scrollTop;
  };
}

synchronizeScrolling(div1, div2)
section {
  display: flex;
  justify-content: space-between;
}

.scroll-box {
  width: 200px;
  height: 200px;
  overflow-y: scroll;
  border: 1px solid #d99;
}

.scroll-box h2 { margin-top: 50px; }
<section>
<div class="scroll-box" id="div1"> 
  <h1>A</h1>
  <h2>B</h2>
  <h2>C</h2>
  <h2>D</h2>
  <h2>E</h2>
  <h2>F</h2>
  <h2>G</h2>
  <h2>H</h2>
</div>

<div class="scroll-box" id="div2"> 
  <h1>1</h1>
  <h2>2</h2>
  <h2>3</h2>
  <h2>4</h2>
  <h2>5</h2>
</div>
<section>

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

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

Is it possible to add padding to an HTML element without affecting its overall dimensions?

Is it possible to apply padding to a div without increasing its size? <div id="someDiv"> someContent </div> #someDiv{ padding: 1em; } One potential solution is to add another nested div within #someDiv and apply margin to that, rathe ...

Having trouble retrieving the default selected value using the index in Angular Material's mat-button-toggle functionality

I'm encountering an issue with setting the default value for a toggle button group. The code is simple and the toggle buttons are correctly fetching values from the index, but I can't seem to get one of them to be default selected. I tried settin ...

Access the most recent state value with React's Context API

Trying out the React context API, Take a look at the someComponent function where I pass the click event (updateName function) to update the value of state.name from the GlobalProvider function. After updating state.name, it reflects in the browser but t ...

The hidden DIV containing an ASP.NET CheckBox consistently yields a value of false

I have a group of form elements located within a hidden div which looks like this: <div id="jDivUpdateFolder" style="display:none;"> <asp:TextBox ID="txtEditFolderName" runat="server"></asp:TextBox><br /> <asp:TextBox ID ...

css Sibling elements restricted within parent container

Encountering an issue with a star rating css example when more than one fieldset is added. The current CSS code seems to be working fine, but it fails when multiple instances of the same elements [fieldset] are present. I've been struggling to find a ...

Turn off background sound on mobile devices

I have a question about the script I'm using to play a background audio theme on my website - is there a way to prevent it from automatically playing on mobile devices? $(document).ready(function() { var audioElement = document.createElement ...

Tips for aligning a div underneath another div in a centered position

I am attempting to align .rij_lessenrooster below .rij_weekdagen so that it is centered under each day. The teacher advised me to create a column and then try it, but it did not resolve the alignment issue. The .rij_weekdagen consistently appears off to th ...

Can MUI FormControl and TextField automatically validate errors and block submission?

Are MUI components FormControl and TextField responsible for error handling, such as preventing a form from being submitted if a required TextField is empty? It appears that I may need to handle this functionality myself, but I would like some clarificatio ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

Registering a function for chart.js plugins that manipulates external data

Is there a way to pass external data to the chart.plugins.register function? I'm struggling because I can't access the necessary context: Chart.plugins.register( { beforeDraw: function (chart) { //implementation } }); I attempted using ...

Establish individual states for every dynamically created component using the same handler function

I have a component in React built with Material UI, where the child component (Paper) is dynamically generated depending on the number of items in an array. The challenge I'm facing is changing the elevation property of the Paper component when it&ap ...

Tips for storing the output of a script URL in a JavaScript variable

I am currently facing an issue with running a script in the 'head' element of a webpage. The script makes an API call to a specific URL and retrieves results in the form of a JavaScript array. However, I am encountering difficulty because the API ...

What is the best way to ensure that the body element is as large as the html element?

My goal is to have the body extend as the page size increases. I attempted setting the height of the body to 100% and the height of the html element to 100%, but it didn't produce the desired outcome: In this illustration, blue represents the body an ...

Styling Overlapping Divs with CSS3

I am attempting to replicate this particular effect using HTML within the UIWebView control on iOS. The desired outcome is to simulate a progress bar on the listing. My current approach involved utilizing this method, however, as you can observe, adding pa ...

Changing a variable in an HTML file using a JavaScript file

I am working with JavaScript code that has been imported from another file containing a variable that I need to update in my HTML file. Is there a way to update the variable without directly inserting the JavaScript code into my HTML document? JavaScript ...

A row divided into three segments in Twitter Bootstrap2, with the second segment spanning the rest

Looking to divide a row into three segments under the following conditions: The first segment should have a maximum height and always stay at the top (minimum height of 0; maximum height of 40%). If the content exceeds the max-height, a scroll bar sho ...

Monitoring individual elements of an array within an Angular service

Is there a way to monitor changes in an array element within a service? Let's consider the following scenario with CartController and ProductListService. Within the ProductListService, data is fetched as follows: /** * Fetch all the products in us ...

What is the best location to insert CSS in an HTML document?

I tried to customize the CSS on my Blogger blog, but unfortunately, I am unable to access the theme designer. As a result, I attempted to add CSS directly into the code using tags. However, I am having trouble locating the tag within the HTML file. This is ...

What is the best way to determine the size of the URLs for images stored in an array using JavaScript?

I am working on a project where I need to surround an image with a specific sized 'div' based on the image's dimensions. The images that will be used are stored in an array and I need to extract the height and width of each image before disp ...