Created
April 26, 2011 14:50
-
-
Save walterdavis/942402 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sticker = $('yourElement'); | |
var origin = sticker.cumulativeOffset(); | |
var width = document.viewport.getWidth(); | |
var offset = 10; //pixels from top | |
var test = new Element('div',{style:'position:fixed'}); | |
var cantBeFixed = (test.style.position.toLowerCase() != 'fixed'); | |
//or, if you also want to simulate the effect on iOS, uncomment the following line | |
//var cantBeFixed = (Prototype.Browser.MobileSafari || test.style.position.toLowerCase() != 'fixed'); | |
sticker['_style'] = sticker.readAttribute('style'); | |
function stick(){ | |
var scrolled = document.viewport.getScrollOffsets()[1]; | |
if(scrolled >= (origin['top'] - offset)){ | |
if(cantBeFixed){ | |
sticker.setStyle({"top":(scrolled + offset) + "px"}); | |
}else{ | |
if(!sticker.stuck){ | |
sticker.setStyle('position:fixed; top:' + offset + 'px; left:' + origin['left'] + 'px;'); | |
sticker['stuck'] = true; | |
} | |
} | |
}else{ | |
sticker.writeAttribute('style',sticker._style); | |
sticker.stuck = false; | |
} | |
} | |
Event.observe(window, 'resize', function(evt){ | |
sticker.writeAttribute('style',sticker._style); | |
sticker.stuck = false; | |
origin = sticker.cumulativeOffset(); | |
stick(); | |
}); | |
Event.observe(window,'scroll', function(evt){ | |
stick(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment