Reputation: 467
I have set up this page so that when you scroll past the top of the navbar, it becomes sticky and stays at the top of the page.
I want it to return to its original position when you scroll back to the top of the page.
Here is a CodePen for the work I have right now. How should I change the jQuery so it sticks back in its original position?
$(window).on('scroll', function () {
var $header = $("#header"),
scrollTop = $(window).scrollTop(),
elementOffset = $header.offset().top,
distance = (elementOffset - scrollTop);
if (distance < 0) {
$header.css({
"position": "fixed",
"top": "0px",
"left": "0",
"right": "0"
});
}
});
Right now, this is how I change the header element into a fixed one as the user scrolls down the page.
Upvotes: 0
Views: 700
Reputation: 4819
Think of the solution in another way:
CSS
.affix {
position:fixed;
top:0;
left:0;
right:0;
}
JS
if (distance < 0) {
$header.addClass("affix");
} else {
$header.removeClass("affix");
}
Upvotes: 1