March 31, 2012
How do I change an attribute of an element when someone scroll pass the element (Sticky Element)
Question by Jonathan Shepherd
For example http://twitter.github.com/bootstrap/base-css.html try to scroll up. You will see the bar with
“Typography Code Tables Forms Buttons Icons by Glyphicons”
when you scroll pass the element it will add a class to make the element change. While you are scrolling back up it will remove the attribute to change the element again.
Edit: I found out this is call Sticky Element.
Answer by Cybrix
THat jQUery plugin can do what you want: http://imakewebthings.com/jquery-waypoints/
And here is an exemple taken from the URL:
someElements.waypoint(function(event, direction) {
if (direction === 'down') {
// do this on the way down
}
else {
// do this on the way back up through the waypoint
}
});
Cheers
Answer by Starx
They are using addClass() function for this
$(".subnav").addClass("subnav-fixed");
Here is the function they are using for this
function processScroll() {
var i, scrollTop = $win.scrollTop() //get the scroll position of the window object
if (scrollTop >= navTop && !isFixed) { //check if its position is higher that the position of the navigation
isFixed = 1 //if yes fix it
$nav.addClass('subnav-fixed')
} else if (scrollTop <= navTop && isFixed) { //if is not higher then
isFixed = 0
$nav.removeClass('subnav-fixed') //un fix it
}
}
And they call this function on the scroll event of the document. May be something like
$(document).scroll(function() {
processScroll();
});