Skip to content

Instantly share code, notes, and snippets.

@adamculpepper
Created January 14, 2015 16:22
Show Gist options
  • Save adamculpepper/11277ca57a89238ad6ce to your computer and use it in GitHub Desktop.
Save adamculpepper/11277ca57a89238ad6ce to your computer and use it in GitHub Desktop.
Sticky Elements (jQuery required)
// demo: http://jsfiddle.net/adamculpepper/mvcjbwbv
$(window).scroll(makeSticky).trigger("scroll");
$(window).load(function () {
$(".sticky-element").each(function () {
var el = $(this);
if (!el.attr("data-offset-top")) {
el.attr("data-offset-top", el.offset().top);
el.attr("data-offset-left", el.offset().left);
}
});
makeSticky();
});
function makeSticky() {
var scrollTop = $(window).scrollTop();
$(".sticky-element").each(function() {
var el = $(this);
var offset = el.attr("data-offset-top");
var left = el.attr("data-offset-left");
var margin = {};
margin.top = el.css("marginTop").replace('px', '');
margin.left = el.css("marginLeft").replace('px', '');
if (scrollTop > offset) {
el.css({
"background": "red", //remove
"position": "fixed"
});
} else {
el.css({
"background": "lightblue", //remove
"position": "static",
"top": 0 - (margin.top*1),
"left": left - (margin.left*1)
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment