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

Generated by cgit