Skip to content

Instantly share code, notes, and snippets.

@blankyao
Created May 26, 2011 01:52
Show Gist options
  • Save blankyao/992399 to your computer and use it in GitHub Desktop.
Save blankyao/992399 to your computer and use it in GitHub Desktop.
jQuery Floating Widget in javascript
(function ($) {
$.fn.floatingWidget = function () {
return this.each(function () {
var $this = $(this),
$parent = $this.offsetParent(),
$window = $(window),
top = $this.offset().top - parseFloat($this.css('marginTop').replace(/auto/, 0)),
bottom = $parent.offset().top + $parent.height() - $this.outerHeight(true),
floatingClass = 'floating',
pinnedBottomClass = 'pinned-bottom';
if ($parent.height() > $this.outerHeight(true)) {
$window.scroll(function () {
var y = $window.scrollTop();
if (y > top) {
$this.addClass(floatingClass);
if (y > bottom) {
$this.removeClass(floatingClass).addClass(pinnedBottomClass);
} else {
$this.removeClass(pinnedBottomClass);
}
} else {
$this.removeClass(floatingClass);
}
});
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment