Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sync scrollbar div to non-scrolled div

I have a web page with three divs that are synced together.

    +----------+
    |   TOP    |
+---+----------+
|   |         ||
| L | CENTER  ||
|   |_________||
+---+----------+

<!--Rough HTML-->
<div>
  <div class="topbar-wrapper">
    <div class="topbar"></div>
  </div>
  <div class="container">
    <div class="sidebar-wrapper">
      <div class="sidebar"></div>
    </div>
    <div class="center-wrapper"> <!-- Set to the window size & overflow:scroll -->
      <div class="center"></div> <!-- Has the content -->
    </div>
  </div>
</div>

The center div has scroll bars, both horizontal and vertical. The top and left divs do not have scroll bars. Instead, when the horizontal scroll bar is moved, the scroll event updates the top div's margin-left appropriately. Likewise when the vertical scroll bar is moved, the margin-top is updated. In both cases, they are set to a negative value.

$('.center-wrapper').scroll(function(e) {
  $('.sidebar').css({marginTop: -1 * $(this).scrollTop()});
  $('.topbar').css({marginLeft: -1 * $(this).scrollLeft()});
});

This works fine in Chrome and Firefox. But in Safari, there is a delay between moving the scroll bar and the negative margin being properly set.

Is there a better way to do this? Or is there some way to get rid of the lag in Safari?

EDIT:

Check out this Fiddle to see the lag in Safari: http://jsfiddle.net/qh2K3/

like image 329
tghw Avatar asked Feb 19 '14 19:02

tghw


1 Answers

Let me know if this JSFiddle works better. I experienced the same "lag" on my end too (Safari 7 on OS X) and these small CSS changes significantly improved it. My best guess is that Safari is being lazy and has not turned on its high-performance motors. We can force Safari to turn it on using some simple CSS:

.topbar-wrapper, .sidebar-wrapper, .center-wrapper {
    -webkit-transform: translateZ(0);
    -webkit-backface-visibility: hidden;
    -webkit-perspective: 1000;
}

This enables hardware accelerated CSS in Safari by offloading some of the work to the GPU. It improves rendering in the browser, which may have been the issue in the delay.

like image 145
Irvin Zhan Avatar answered Oct 09 '22 04:10

Irvin Zhan