Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing an element when it reaches the top of the page

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}.

Site

The <header> element is the sidebar on the right with the big green demo button.

like image 633
Sebastian Avatar asked Nov 30 '22 11:11

Sebastian


2 Answers

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;
}

DEMO

like image 79
James Avatar answered Dec 11 '22 11:12

James


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.

like image 45
Mathew MacLean Avatar answered Dec 11 '22 09:12

Mathew MacLean