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

When the modal is closed, the textarea data remains intact, while the model is cleared

My challenge involves a simple modal that includes a text area. The issue I am facing is resetting the data of the textarea. Below is the modal code: <div class="modal fade" ng-controller="MyCtrl"> <div class="modal-dialog"> <d ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Is it possible to click the back button on your browser and return to an ajax page while keeping it in the same appearance?

I've been researching different jquery history plugins, but I haven't come across any examples that fit my specific situation. This is leading me to believe that what I'm trying to accomplish may not be feasible. Our search page is highly c ...

Tap to navigate to queued sections on click

Greetings, community members! Despite my extensive research, I have been unable to find a solution to my query. Just a heads up - I am a novice when it comes to javascript and jQuery. My question pertains to incorporating two image buttons that, upon cli ...

What is the best way to retrigger an ajax request in jQuery after it encounters an error?

In my JavaScript code, I have an AJAX request that communicates with a Rails controller to send data. If the controller detects duplicate information already in the database, it returns an 'Unprocessable Entity' error. I am looking to implement ...

Does utilizing this.someFunction.bind(this) serve a purpose or is it duplicative

As I analyze someone's code, I stumbled upon the following snippet: this.device_name.changes().onValue(this.changeName.bind(this)) My interpretation so far is that onValue requires a callback function, which in this case is this.changeName.bind(this ...

How to Stop AJAX Requests Mid-Flight with JQuery's .ajax?

Similar Question: Stopping Ajax Requests in JavaScript with jQuery Below is the straightforward piece of code that I am currently using: $("#friend_search").keyup(function() { if($(this).val().length > 0) { obtainFriendlist($(this).va ...

When attempting to transfer data from an Ajax HTML form to a Flask template in Python upon clicking a button, encountered difficulties

I am a beginner with Flask and HTML. I need some help as I am struggling to retrieve parameter values from the HTML form (index1.html). Here is my HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Should you stick with pre-defined styles or switch to dynamic inline style changes?

I am currently developing a custom element that displays playing cards using SVG images as the background. I want to make sure that the background image changes whenever the attributes related to the card's suit or rank are updated. From what I under ...

Is there a way for me to choose every element excluding those contained within a specific div?

Check out my code snippet: <div class="car"> <div class="make">NISSAN</div> <div class="model">MICRA</div> </div> <div class="discontinued"> <div class="car"> <div class="make">FOR ...

How do I implement a dynamic input field in Angular 9 to retrieve data from a list or array?

I'm looking to extract all the strings from the Assignes array, which is a property of the Atm object, and populate dynamic input fields with each string. Users should be able to update or delete these strings individually. What approach can I take us ...

I am experiencing an issue with my jQuery ajax where my return function is not working as expected

I'm currently working on the following code snippet: $("#upvote").click(function(){ var up = parseInt(document.getElementById('voteScore').innerHTML); up++; document.getElementById('voteScore').innerHTML = up; $.aj ...

Is there a way to prevent certain words or letters from being exchanged in PHP?

In my PHP project, I am trying to replace text in one textarea and display it in another. While most of the code works fine, there are some parts that are causing issues. Currently, I am using the str_ireplace function with around 60 different words and m ...

What sets declaring variables apart in Vue?

Can you clarify the distinctions among various methods of declaring variables? When should I employ each of these declaration methods? <script> const someVariable = 12345 export default { name: 'App', } </script> <script> e ...

Provide the aggregated content within d3's text() or html() function

Below is my d3 code snippet: grouping.append('foreignObject').html(function (d) { var string = '<p>hello, {{ "there" }} <some-directive></some-directive></p>'; string = $compile(string)(scope); return stri ...

I am having trouble getting bootstrap-icons to work in my Angular project and I'm eager to figure it out

I am having trouble incorporating bootstrap-icons into my angular project. Despite running the npm i bootstrap-icons command, I am unable to successfully add icons using icon fonts on my webpage. As a temporary solution, I have added the bootstrap icon CD ...

React js background image not filling the entire screen

Having experience with React Native, I decided to give ReactJS a try. However, I'm struggling with styling my components because CSS is not my strong suit. To build a small web application, I am using the Ant Design UI framework. Currently, I have a ...

Experiencing issues with the session not functioning properly on the login page

After setting up Centos 6.4 on my HP Server with PHP 5.3.3, Apache 2.2.15, and Mysql 5.1.69, I encountered login issues where it always fails. Here is the source code: index.php <? include "functions.php"; start_session(); session_destroy(); start_ ...

Error: The function "navigate" has not been declared or defined

Just starting out in reactjs and embarking on a new project. I've successfully implemented a register and login function using firebase, but hit a snag when trying to navigate to a new page like the dashboard upon user login, I encountered this error: ...

How can I add a character at a precise location while keeping the existing tags intact

Latest Update After further testing, it seems that the code performs well with a faux spacer, but runs into issues with the regex. The following scenarios work correctly: Selecting words above or below the a tag Selecting just one line directly above or ...