Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronize two scrollbars for divs

Tags:

javascript

css

I have this code for file compares: http://jsfiddle.net/CrN6X/

Now it does what I need:

  1. One big div that scrolls only vertically
  2. Two smaller dives that scroll only horizontally

This way I can compare my files pretty easy, but I have one problem: the bottom scrollbars are accessable only when I scroll all the way down.

How can I make them float or move the scrollbar to another div, that can bee seen always, so that I don't need to scroll down the other div all the way to the bottom to access them?

like image 777
Peon Avatar asked Aug 20 '12 13:08

Peon


2 Answers

The javascript in this is what you need really, but I added the html so you can see it in action.

$("#div1").scroll(function () { 
  $("#div2").scrollTop($("#div1").scrollTop());
  $("#div2").scrollLeft($("#div1").scrollLeft());
});
$("#div2").scroll(function () { 
  $("#div1").scrollTop($("#div2").scrollTop());
  $("#div1").scrollLeft($("#div2").scrollLeft());
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<div id="div1" style="float:left;overflow:auto;height:100px;width:200px;">
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
</div>

<div id="div2" style="float:right;overflow:auto;height:100px;width:200px;">
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
</div>
like image 140
Ryan McDonough Avatar answered Oct 08 '22 06:10

Ryan McDonough


To avoid scrolling lags effect when using the mousewheel to scroll, we need to disable the second scroll event trigger. Check my approach below:

  var ignoreScrollEvents = false
  function syncScroll(element1, element2) {
    element1.scroll(function (e) {
      var ignore = ignoreScrollEvents
      ignoreScrollEvents = false
      if (ignore) return

      ignoreScrollEvents = true
      element2.scrollTop(element1.scrollTop())
    })
  }
  syncScroll($("#div1"), $("#div2"))
  syncScroll($("#div2"), $("#div1"))
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>

<div id="div1" style="float:left;overflow:auto;height:100px;width:200px;">
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
</div>

<div id="div2" style="float:right;overflow:auto;height:100px;width:200px;">
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
  <p>lulz</p>
</div>
like image 22
Nilton Vasques Avatar answered Oct 08 '22 06:10

Nilton Vasques