Sunday, May 04, 2014

Position Sticky Workaround

Position Sticky is not here yet.
http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit

Demo: http://jsbin.com/omanut/1343
<!--http://updates.html5rocks.com/2012/08/Stick-your-landings-position-sticky-lands-in-WebKit->
<style>
body {
margin: 0;
text-align: center;
font-family: sans-serif;
}
.fixed {
position: fixed;
top: 0;
}
.sticky {
width: 100%;
background: #F6D565;
padding: 25px 0;
text-transform: uppercase;
}
</style>
<p style="margin-bottom:100px;">Scroll this page.</p>
<div class="sticky"><h3>Super amazing header</h3></div>
<p style="margin-top:500px;">Still there?</p>
<p style="margin-top:500px;">Yep!</p>
<p style="margin-top:500px;">Scroll so hard!</p>
<script>
var sticky = document.querySelector('.sticky');
var origOffsetY = sticky.offsetTop;
function onScroll(e) {
window.scrollY >= origOffsetY ? sticky.classList.add('fixed') :
sticky.classList.remove('fixed');
}
document.addEventListener('scroll', onScroll);
</script>

No comments: