1

I'm trying to keep a header on top of the page using JavaScript. position: fixed cannot be used because the header needs to be scrolling horizontally. Keeping it on top is easy but making it smooth is problematic. For some users it's smooth in Chrome but it's laggy on Safari for everyone.

Here is an example: http://jsbin.com/bufejapuza/edit?html,css,js,output

How do I keep the header fixed on top so that it won't be janky while scrolling.

Edit: To get it lagging in Chrome, try toggling the HTML, CSS & JS tabs in JSBin.

3
  • I see the top bar is static not Junky while scrolling! Commented Aug 19, 2016 at 8:31
  • @Smit which browser and OS? Commented Aug 19, 2016 at 8:35
  • @Smit please try it on Safari Commented Aug 19, 2016 at 8:36

1 Answer 1

4
+50

Use position fixed and adjust X dynamically, not Y

  • Change header position to fixed
  • Adjust the x-pos by JavaScript
  • No jank while scrolling vertically
function setLocation() {
  var left = -window.scrollX;  
  header.style.transform = "translateX(" + left + "px)";
}

I tested this in Firefox and Safari (both Mac) and it fixed the problem.

Modified JS Bin

Sign up to request clarification or add additional context in comments.

5 Comments

Because it uses position fixed.
But the other way uses position absolute which makes horizontal scrolling smooth. Why does it not lag horizontally when that doesn't use fixed positioning?
Your code does not change anything while scrolling horizontally, therefore we don't see any jank. ;-)
That doesn't explain why switching on which axis we use CSS and JS changes the performance of scrolling.
You are right. What solves the jank problem is the use of position fixed. As fixed takes care of Y, we need to adjust X, only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.