Created
July 23, 2015 09:15
-
-
Save yadomi/423ca5eda5d44a19140d to your computer and use it in GitHub Desktop.
jQuery plugin to stick element when scrolling
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
$.fn.stickMe = function(options) { | |
return this.each(function() { | |
var $this = $(this); | |
function onScroll() { | |
var topToElementStart = $this.offset().top - (options.startOffset + options.offset); | |
var topToViewportTop = $(window).scrollTop(); | |
var topToViewportBottom = $(window).scrollTop() + $(window).height(); | |
var topToElementEnd = $this.offset().top + options.height; | |
if( topToViewportTop > topToElementStart ) { | |
if (topToViewportBottom < topToElementEnd ) { | |
options.toStick.addClass('sticky'); | |
} | |
} else { | |
options.toStick.removeClass('sticky'); | |
} | |
if (topToViewportBottom > topToElementEnd ) { | |
options.toStick | |
.addClass('sticky-end') | |
.removeClass('sticky') | |
.css({top: (options.height - options.toStick.height() - options.offset) + 'px' }); | |
} else { | |
options.toStick | |
.removeClass('sticky-end') | |
.removeAttr('style'); | |
} | |
} | |
$(window).scroll(onScroll); | |
onScroll(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment