JavaScript Menu That Scrolls With the Page

It took me forever to figure this out, so I’m recording it here so I don’t have to figure it out again next time.

The gist of it is that you create an element that’s positioned somewhere on a page. When you scroll down, the object moves down with the page, so it’s in a fixed spot no matter how far down you scroll. Just stick all this in the head of your document:

<b>JavaScript</b>
window.onscroll = document.documentElement.onscroll = function() {
  var obj = document.getElementById('confirm');
  if (!obj) return;
  var currentOffset = document.body.scrollTop || document.documentElement.scrollTop;
  var desiredOffset = currentOffset + 20;
  if (desiredOffset != parseInt(obj.style.top)) 
    obj.style.top = desiredOffset + 'px';
}
<b>CSS</b>
#confirm {
  position: absolute;
  left: 640px;
  top: 20px;
  width: 200px;
  height: 100px;
}

Leave a Reply