Skip to content

Instantly share code, notes, and snippets.

@walterdavis
Created April 26, 2011 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walterdavis/942402 to your computer and use it in GitHub Desktop.
Save walterdavis/942402 to your computer and use it in GitHub Desktop.
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