I currently have a script that fixes a <header>
element after a certain amount of scrolling. How would I modify it so that the element scrolls normally until it gets to the top of the page then fixes. Something like this.
Current code:
$(document).ready(function(){
// Fix Sidebar
windowHeight = $(window).height();
sidebarHeight = $(".sidebar").height() + 70;
console.log(sidebarHeight + ", " + windowHeight);
if (windowHeight > sidebarHeight) {
$('.sidebar').addClass("affix");
}
});
N.B. .affix
is just {position:fixed}
.
The <header>
element is the sidebar on the right with the big green demo button.
To make your sidebar fixed when the user scrolls down and reaches the top of the sidebar, use Jquery to add a class name to the sidebar when it reaches the window top position and add the position:fixed
style to this new class.
var stickySidebar = $('.sidebar').offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() > stickySidebar) {
$('.sidebar').addClass('affix');
}
else {
$('.sidebar').removeClass('affix');
}
});
This will add a class name affix
to the sidebar
when the user scrolls down and reaches the top of the sidebar. Now add the fixed position to the sidebar
with class name affix
.
.sidebar.affix{
position:fixed;
top:0;
right:0;
}
I believe you may be looking for something like this: http://stickyjs.com/ (scroll to see it in action, you can do this to any element on a page). If that isn't what you are looking for let me know and I will help come up with something that suits your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With