0

I can't find a way to synchronize two divs, with the same text, but different text size and padding. I have two divs, one with a markdown text, and the other one with the html render of the markdown and I want to synchronize the scrollTop between the divs.

For an example, look stackedit.io

TaoPR
  • 5,932
  • 3
  • 25
  • 35
Akaron
  • 33
  • 1
  • 4

1 Answers1

1

You can see the example of synchronizing two divs at: JSFiddle

HTML

Given you have two divs placed next to each other horizontally. Each of the divs contain another div and it is scrollable vertically:

<div class="outer" id="div1">
    <div>
    </div>
</div>
<div class="outer" id="div2">
    <div>
    </div>
</div>

CSS

This is just to make two outer divs lie next to each other at the same baseline and make it scrollable vertically.

div.outer
{
    display:inline-block;
    width:150px;
    height:320px;
    border:1px solid black;
    overflow-y:auto;
}

div.outer > div
{
    width:100%;
    height:3000px;
}

JavaScript

The simplest approach is, bind scroll event to each of the outer divs, take the scrollTop value and apply to its counterpart div as follows:

$('#div1').scroll(function(){
    $('#div2').scrollTop( $('#div1').scrollTop() );
});

$('#div2').scroll(function(){
    $('#div1').scrollTop( $('#div2').scrollTop() );
});

So when you scroll on the left div, it synchronizes the right div, and vice-versa.

TaoPR
  • 5,932
  • 3
  • 25
  • 35
  • This doesn't really work if your generated preview is larger than your markdown. See [updated fiddle](http://jsfiddle.net/mvn1ngby/6/). Stackedit calls this "scroll link" feature (see their README). The code for this extension is [open-source](https://github.com/benweet/stackedit/blob/82ba08fbfdc0c64036453d6fab24027565e5409c/public/res/extensions/scrollSync.js). Would be cool to have this decoupled from their code. This enables to align varies content depending on the current view port. – user2715478 May 04 '16 at 23:05