Skip to content

Instantly share code, notes, and snippets.

@mhayes

mhayes/README.md

Created Dec 4, 2013
Embed
What would you like to do?
Make elements sticky on a page

Quickstart

  1. Add jquery.makeitsticky.js to your page
  2. Decide which element you want to make sticky, and initiliaze like so: $('#myElement').makeItSticky()

Options

  • threshold: Number of pixels from the top of the page when an element should become sticky (default: 20)
  • stickyClass: The fixed position class to apply to an element (default: fixed)
  • mobileBreakpoint: The number of pixels when your design snaps into mobile view, will undo any sticky classes applied. (default: 767)
$('#myElement').makeItSticky({
  threshold: 20,
  stickyClass: 'fixed',
  mobileBreakpoint: 767
});
$.fn.makeItSticky = function(options) {
var settings = $.extend({
fixedClass: "fixed",
threshold: 20,
mobileBreakpoint: 767
}, options);
var self = this;
self.data('top-offset', self.offset().top);
$(window).on('resize.makeItSticky', function(){
var w = $(this),
fixed = self.hasClass('fixed');
if (w.width() <= settings.mobileBreakpoint) {
self.removeClass('fixed');
return true;
}
if (fixed) self.removeClass('fixed');
self.data('top-offset', self.offset().top);
if (fixed) self.addClass('fixed');
});
$(window).on('scroll.makeItSticky', function(e){
var w = $(this),
scrollTop = $(this).scrollTop(),
elTop = self.data('top-offset') - settings.threshold;
if (w.width() <= settings.mobileBreakpoint) {
self.removeClass('fixed');
return true;
}
if (scrollTop > elTop) {
if (!self.hasClass('fixed')) self.addClass('fixed');
} else {
if (self.hasClass('fixed')) self.removeClass('fixed');
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.