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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!