Scroll two blocks at the same time vertically with jQuery

Posted on: Nov 11, 2017 by admin

Scrolling two blocks at the same time can be done with a simple piece of code, with jQuery. This type of scrolling is mostly used when comparing the content of two blocks, so we can easily detect differences.

I have create a simple code where two divs can be scrolled at the same time in vertical direction. Below you can find download and demo link.

DOWNLOAD  DEMO

 

Code Explanation

1) HTML code

Html is the easiest language for any developer. I have created two divs with column1 and column2 classes which will be used by jQuery selectors to trigger scroll events.

 

2) CSS code

Styling of html may vary by your preferences, however its important that the block you want to scroll, to have overflow-y:scroll; and the height that you desire.
Here is my CSS code.

 

.column1{float:left; max-width:340px; width:100%; height:200px; overflow-y:scroll;margin-right: 20px}
.column2{float:right; max-width:340px; width:100%; height:200px; overflow-y:scroll;}

 

3) jQuery Code

Here comes the most important part of the scrolling function. Firstly we set an mouseenter event which will trigger the scroll event. After that we will need a mouseleave event which will reset the scroll properties of the current hovered block.

This way the scrolling will be simultaneous. Meaning, when we scroll column1, the column2 scrolls the same way as column1 and when we scroll column2, the column1 will scroll the same way as column2. If we dont create the mouseleave event, the simultaneous scroll will happen only when we scroll column1 div.

 

$('.column1').on('mouseenter', function(){
   $('.column1').on('scroll', function () {
      $('.column2').scrollTop($(this).scrollTop());
   });
});

$('.column1').on('mouseleave', function(){
   $('.column1').off('scroll');
   $('.column2').off('scrollTop');
});

$('.column2').on('mouseenter',function(){
   $('.column2').on('scroll', function () {
      $('.column1').scrollTop($(this).scrollTop());
   });
});

$('.column2').on('mouseleave', function(){
   $('.column2').off('scroll');
   $('.column1').off('scrollTop');
});

 

The code inside the article is for demonstration purpose only. The links above provide full and structured code.

Comments