Divs that Move When Users Scroll

Today I was working on a project that has a search box at the top of the page in the primary nav bar that I thought would be nice if it stayed put when scrolling through the hundreds of lines of data on the page. I thought, Moving elements on a page must entail javascript, right?.

Wrong

With Javascript

But alas, I started down the JavaScript path anyways. So I can cut to the chase a bit sooner, I’ll just paste the function I wrote so those of you out there who want to use Javascript can.

function setScrollable(ScrollObject) {
  ScrollObject.style.top=window.pageYOffset+'px';
  ScrollObject.style.left=window.pageXOffset+'px';
}

To use that function, you need several things. First, you need the onscroll event in your body tag.

<body onscroll="setScrollable(document.getElementById('ScrollDiv'));">

Finally, you need one thing set in your styles (perhaps two, depending on if you’re using z-values)…​

div#ScrollDiv {
 position:absolute;
 z-index:100;
}

And presto! You’ve got yourself a div that moves up, down, left, and right when your user scrolls.

You will however likely notice that when you scroll quickly, the bar flickers. Well, it doesn’t flick. It’s more like it your browser doesn’t process the JavaScript fast enough for the bar to stay at the top during an onscroll event ergo, it takes a few to catch up. I thought to myself, How does Google pull this off so seamlessly with their in-browser chat windows that stay put so nicely at the bottom right hand of your screen whilst scrolling? (oh yes, whilst was in that thought). After looking around for a while, it hit me that you can use CSS to do this.

With CSS

As it turns out, that fancy property we all use to keep our backgrounds from scrolling on our pages also works with objects. To implemenet this the CSS way, all you need to do it put in a bit of styling to position your div (or whatever object you want stationary) and your’e set.

div#ScrollDiv {
 position:fixed;
}

Sweet mother, that was easy!

Last edited: 2019-09-28 23:22:07 UTC