Created
January 14, 2015 16:22
-
-
Save adamculpepper/11277ca57a89238ad6ce to your computer and use it in GitHub Desktop.
Sticky Elements (jQuery required)
This file contains hidden or 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
// 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