Last active
September 29, 2015 00:48
-
-
Save Mantish/1522267 to your computer and use it in GitHub Desktop.
jQuery plugin to have divs stick to the top of the screen (or at some distance from the top), once scrolled by.
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
(function($) | |
{ | |
$.fn.stickytitle = function(options) | |
{ | |
var opts = $.extend($.fn.stickytitle.defaults, options); | |
var elements = this, starting_offsets = new Array(); | |
elements.each(function(index){ | |
//before anything happens, the original top offsets of each element are saved | |
starting_offsets[index] = $(this).offset().top; | |
}); | |
var scrolledBy = function(element, index) | |
{ | |
return $(window).scrollTop() + opts['gap'] >= starting_offsets[index]; | |
} | |
$(window).on('scroll', function(e){ | |
elements.each(function(index){ | |
var is_sticky = scrolledBy(this, index); | |
$(this).toggleClass('sticky-title', is_sticky); | |
//position fixed is given to elements that are scrolled by | |
//filler divs are created to fill the gap | |
if (is_sticky){ | |
if ($(this).next('.filler_div').length == 0){ | |
var $filler_div = $(document.createElement('div')); | |
var filler_div_css = { | |
'height' : $(this).css('height'), | |
'paddingTop' : $(this).css('paddingTop'), | |
'paddingBottom' : $(this).css('paddingBottom'), | |
'marginTop' : ( parseInt($(this).css('marginTop')) + parseInt($(this).css('borderTopWidth')) ) + 'px', | |
'marginBottom' : ( parseInt($(this).css('marginBottom')) + parseInt($(this).css('borderBottomWidth')) ) + 'px' | |
} | |
$filler_div.addClass('filler_div').css(filler_div_css); | |
$(this).after($filler_div); | |
} | |
$(this).css({'position': 'fixed', 'top': opts['gap']+'px'}); | |
}else{ | |
$(this).next('.filler_div').remove(); | |
//remove inline styles | |
if (this.style.removeProperty){ | |
this.style.removeProperty('position'); | |
this.style.removeProperty('top'); | |
}else{ | |
this.style.removeAttribute('position'); | |
this.style.removeAttribute('top'); | |
} | |
} | |
}); | |
}); | |
return this; | |
} | |
$.fn.stickytitle.defaults = { | |
gap: 0 | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment