Skip to content

Instantly share code, notes, and snippets.

@chaupt
Created December 4, 2010 21:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save chaupt/728487 to your computer and use it in GitHub Desktop.
Save chaupt/728487 to your computer and use it in GitHub Desktop.
Patched version of stickyFloat.js, a smart sticky floating box jQuery plugin
/*
* stickyfloat - jQuery plugin for verticaly floating anything in a constrained area
*
* Example: jQuery('#menu').stickyfloat({duration: 400});
* parameters:
* duration - the duration of the animation
* startOffset - the amount of scroll offset after it the animations kicks in
* offsetY - the offset from the top when the object is animated
* lockBottom - 'true' by default, set to false if you don't want your floating box to stop at parent's bottom
* $Version: 05.16.2009 r1
* Copyright (c) 2009 Yair Even-Or
* vsync.design@gmail.com
* Mods by: Christopher Haupt, Webvanta Inc.
* http://www.webvanta.com/, http://twitter.com/chaupt, http://github.com/chaupt
* Honor options set by user.
*/
$.fn.stickyfloat = function(options, lockBottom) {
var $obj = this;
var parentPaddingTop = parseInt($obj.parent().css('padding-top'));
var startOffset = $obj.parent().offset().top;
var opts = $.extend({ startOffset: startOffset, offsetY: parentPaddingTop, duration: 200, lockBottom:false }, options);
$obj.css({ position: 'absolute' });
if(opts.lockBottom){
var bottomPos = $obj.parent().height() - $obj.height() + opts.offsetY; //get the maximum scrollTop value
if( bottomPos < 0 )
bottomPos = 0;
}
$(window).scroll(function () {
$obj.stop(); // stop all calculations on scroll event
var pastStartOffset = $(document).scrollTop() > opts.startOffset; // check if the window was scrolled down more than the start offset declared.
var objFartherThanTopPos = $obj.offset().top > opts.startOffset; // check if the object is at it's top position (starting point)
var objBiggerThanWindow = $obj.outerHeight() < $(window).height(); // if the window size is smaller than the Obj size, then do not animate.
// if window scrolled down more than startOffset OR obj position is greater than
// the top position possible (+ offsetY) AND window size must be bigger than Obj size
if( (pastStartOffset || objFartherThanTopPos) && objBiggerThanWindow ){
var newpos = ($(document).scrollTop() - opts.startOffset + opts.offsetY );
if ( newpos > bottomPos )
newpos = bottomPos;
if ( $(document).scrollTop() < opts.startOffset ) // if window scrolled < starting offset, then reset Obj position (opts.offsetY);
newpos = opts.offsetY;
$obj.animate({ top: newpos }, opts.duration );
}
});
};
@yairEO
Copy link

yairEO commented Apr 8, 2012

I am the author of this plugin, and I recently changed much of the code, to fix many things and refactor stuff.

http://dropthebit.com/74/sticky-floating-box/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment