Sticky (position absolute or fixed depending on visibility)

In response to a question at http://stackoverflow.com/questions/16441226/always-show-a-div-as-soon-as-its-not-visible-any-more-after-scrolling-down/16441526

by Barney Carroll

HTML

<div id="stick">
    I should be fixed… sometimes
</div>

CSS

#stick {
    position: absolute;
    top: 60px;
}

#stick.fixed {
    position: fixed;
    top: 0;
}

/* To make scrolling applicable... */

body {
    height: 99em;
}

JavaScript

var stick = document.getElementById('stick');

window.onscroll = function(){
    if(stick.getBoundingClientRect().top < 0){
        stick.className = 'fixed';
    } else if(stick.className.indexOf('fixed') < 0) {
        stick.className = '';
    }
}