How to change attribute of an element when someone scrolls the element (Sticky Element)

For example try scrolling up. You will see a panel with

"Typography Code Tables Button Shapes Icons Using Glyphicon"

when you scroll through the passage, the element will add a class to change the element. While you scroll back, it will remove the attribute to change the element again.

Edit: I found out that this is a Sticky Element call.


source to share

3 answers

This jQuery plugin can do what you want:

And here's an example 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





They use the addClass () function for this



Here is the function they use to do 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
} 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 document scroll event. Maybe something like

$(document).scroll(function() {




They keep track of the scroll position and change the class on the li elements

The sub-navigation bar you see 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>


Notice how they set class = 'active' on the navigation element they want to activate.

With JQuery, you need to select that li element and change its class. There are many ways to select the element you want (by id, child selector, class selector, etc.) See

to change the class you can use the 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 it :contains

can be a little cumbersome as it searches for all text inside the selected element. You can use other selectors like: eq or nth-child See

$("ul.nav li:eq(2)").addClass( "active");




All Articles