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.
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();
});
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
They are tracking the scroll position and modifying the class on the li elements
The sub-navigation bar you are seeing is implemented using ul and li elements. You can see from firebug:
<div class="subnav subnav-fixed">
<ul class="nav nav-pills">
<li class=""><a href="#typography">Typography</a></li>
<li class=""><a href="#code">Code</a></li>
<li class="active"><a href="#tables">Tables</a></li>
<li class=""><a href="#forms">Forms</a></li>
<li class=""><a href="#buttons">Buttons</a></li>
<li class=""><a href="#icons">Icons by Glyphicons</a></li>
</ul>
</div>
Notice how they are setting class='active' for the navigation element they want to make active.
With Jquery, you need to select that li element and change it class. There are many ways to select the element you want (by id, child selector, class selector etc) See http://api.jquery.com/category/selectors/
to change the class, you can use toggleClass, addClass and removeClass functions to manipulate the class of the element you want
For example, you could do
//remove any active elements
$("ul.nav > li").removeClass("active");
//Make the 'Tables' subnav element active
$("ul.nav > li:contains('Tables')").addClass("active");
Note that :contains
might be a little heavy since it looks for all text inside the selected element. You can use other selectors such as :eq or nth-child See http://api.jquery.com/nth-child-selector/
$("ul.nav li:eq(2)").addClass( "active");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.