Skip to content

Instantly share code, notes, and snippets.

@gjrevans
Created August 24, 2018 19:36
Show Gist options
  • Save gjrevans/e027e45a555f33e729152758c298e741 to your computer and use it in GitHub Desktop.
Save gjrevans/e027e45a555f33e729152758c298e741 to your computer and use it in GitHub Desktop.
/**
* JS ScrollFix
* Fixes an element to the top of a page at a certain scroll height
* *
* @author Avail
* @copyright Copyright (c) 2017
* @since Version 1.0.0
*
*/
(function( $ ) {
$.fn.fixedTop = function() {
return $(this).each(function() {
// Create scoped variables
var $element = $(this),
position = $element.offset().top,
height = $element.outerHeight();
// Detect scroll position
$(window).scroll(function() {
// Detect distance from top on scroll
var distance = $(window).scrollTop();
if (distance >= position) {
$("body").css("padding-top", height);
$element.addClass("fixed-top");
} else {
$("body").css("padding-top", 0);
$element.removeClass("fixed-top");
}
});
});
};
}( jQuery ));
// Initialize our count function on anything with the js-count class
$(function() {
$(".js-fixed").fixedTop();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment