Reputation: 717
I want an element of my websites's sidebar to be fixed after some scrolling. The functionality i'm searching is the same used by 9gag website here: http://9gag.com/gag/abq3PbX?ref=fsidebar (specifically the last square ads that is fixed when you scroll down the page from some point). How can i do the same without using jquery or other external libraries, but using css/javascript only?
Upvotes: 2
Views: 1994
Reputation: 66
I've done by switching between 'fixed' and 'absolute' regarding the document's body scrollTop.
function scrollFunction() {
var scrollPos = document.body.scrollTop;
if (scrollPos > 40) {
document.getElementById("fixed-floater").style.position = "fixed";
document.getElementById("fixed-floater").style.top = "0px";
} else {
document.getElementById("fixed-floater").style.position = "absolute";
document.getElementById("fixed-floater").style.top = "40px";
}
}
window.onscroll = scrollFunction;
http://jsfiddle.net/ua4fhrzy/1/
But you might consider looking into "sticky css"
Upvotes: 3