In case you have two divs of different sizes you may sometimes want to scroll both at the same time but at different speeds depending on their size. For example, you could have text in one and images in the other and want to scroll both at the same time. To achieve this, we will do it with the jQuery JavaScript library.
And no....jQuery is not dead.
To synchronize the scroll positions we can use .scrollTop() to know the position of the content with respect to the top of the page.
First, we place the page div with the main content and then the block div with the secondary content that will scroll with respect to the main one according to its position. This second div will have to have a fixed position with respect to the page. That is to say, that in its CSS it will have to contain the artribute "position: fixed".
<div id="mypage">
<p class="mypageHeader">my page header</p>
<p>Here we place our text</p>
.........
<p>more text...</p>
<p> class="footerPage">footer page</p>
</div>
<div id="box">
<div id="boxHeight">
<p class="boxheader">box header</p>
<p>Here we place our text</p>
.........
<p>more text</p>
<p class="boxfooter">footer box</p>
</div>
</div>
Let's go now with the JavaScript code. In pageH we get the difference between the height of the page div and the height of the window to calculate the height of the non-visible content. In pagT we get the scroll position of the window minus the height that we have already advanced in the page div.
Finally we move the block div correspondingly with respect to the page div so that they move the same proportional distance based on their height.
$(window).scroll(function() {
var pagH = $('#mypage').height() - $(this).height();
var pagT = this.scrollY - $('#mypage').offset().top;
$('#box').scrollTop(pagT / pagH * ($('#boxHeight').height() - $(this).height()));
});
The styles of the divs are as follows:
body {
position: relative;
margin: 0 auto;
}
#mypage {
position:relative;
width: 550px;
}
#mypage p {
text-align: justify;
}
#box {
background: #027EBA;
display: block;
width: 200px;
height: 100%;
position: fixed;
right: 20px;
top:0;
overflow: hidden;
}
.mypageHeader, .footerPage {
display: block;
width: 100%;
margin: 0 auto;
background: red;
color: white;
font-weight: bold;
font-size: 16px;
}
.boxheader, .boxfooter {
display: block;
width: 100%;
margin: 0 auto;
background: green;
color: white;
font-weight: bold;
font-size: 16px;
}
IMPORTANT: don't forget to add jQuery.