summaryrefslogtreecommitdiff
path: root/posts/Divs_That_Move_When_Users_Scroll.adoc
blob: a4fe24c570ef546ce448d05cdfb7f246ad6b9e55 (plain)
    1 Divs that Move When Users Scroll
    2 ================================
    3 :author: Aaron Ball
    4 :email: nullspoon@iohq.net
    5 
    6 
    7 Today I was working on a project that has a search box at the top of the page
    8 in the primary nav bar that I thought would be nice if it stayed put when
    9 scrolling through the hundreds of lines of data on the page. I thought, 'Moving
   10 elements on a page must entail javascript, right?'.
   11 
   12 Wrong
   13 
   14 
   15 [[with-javascript]]
   16 === With Javascript
   17 
   18 But alas, I started down the JavaScript path anyways. So I can cut to
   19 the chase a bit sooner, I'll just paste the function I wrote so those of
   20 you  out there who want to use Javascript can.
   21 
   22 ----
   23 function setScrollable(ScrollObject) {
   24   ScrollObject.style.top=window.pageYOffset+'px';
   25   ScrollObject.style.left=window.pageXOffset+'px';
   26 }
   27 ----
   28 
   29 To use that function, you need several things. First, you need the onscroll
   30 event in your body tag.
   31 
   32 ----
   33 <body onscroll="setScrollable(document.getElementById('ScrollDiv'));">
   34 ----
   35 
   36 Finally, you need one thing set in your styles (perhaps two, depending on if
   37 you're using z-values)...
   38 
   39 ----
   40 div#ScrollDiv {
   41  position:absolute;
   42  z-index:100;
   43 }
   44 ----
   45 
   46 And presto! You've got yourself a div that moves up, down, left, and right when
   47 your user scrolls.
   48 
   49 You will however likely notice that when you scroll quickly, the bar flickers.
   50 Well, it doesn't flick. It's more like it your browser doesn't process the
   51 JavaScript fast enough for the bar to stay at the top during an onscroll event
   52 ergo, it takes a few to catch up. I thought to myself, 'How does Google pull
   53 this off so seamlessly with their in-browser chat windows that stay put so
   54 nicely at the bottom right hand of your screen whilst scrolling?' (oh yes,
   55 whilst was in that thought). After looking around for a while, it hit me that
   56 you can use CSS to do this.
   57 
   58 
   59 [[with-css]]
   60 === With CSS
   61 
   62 As it turns out, that fancy property we all use to keep our backgrounds
   63 from scrolling on our pages also works with objects. To implemenet this
   64 the CSS way, all you need to do it put in a bit of styling to position
   65 your div (or whatever object you want stationary) and your'e set.
   66 
   67 ----
   68 div#ScrollDiv {
   69  position:fixed;
   70 }
   71 ----
   72 
   73 Sweet mother, that was easy!
   74 
   75 
   76 Category:CSS
   77 Category:HTML
   78 Category:JavaScript
   79 
   80 
   81 // vim: set syntax=asciidoc:

Generated by cgit