Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Add class depending on scrolling

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #154437
    Leonard
    Participant

    Hello!

    I wanted to add an active-class to an element depending on if the user scrolls over a specific element.
    If the user is not scrolling over the element anymore the class should disappear again.

    I want to use this for my navigation like here:
    (http://screenr.com/U3YH “Example”)

    Thank you!

    #154472
    Senff
    Participant

    You’re going to have to detect the scroll position of your page and the (vertical) position of the sections on your page, and then based on that, give the corresponding menu item in your menu a specific class.

    http://api.jquery.com/scrollTop/
    http://api.jquery.com/position/

    Something like this (not tested):

    if ( $('body').scrollTop() > $('.section-a').position.top ) {
        $('.menu-items').removeClass('selected');
        $('.menu-a').addClass('selected');
    }
    
    if ( $('body').scrollTop() > $('.section-b').position.top ) {
        $('.menu-items').removeClass('selected');
        $('.menu-b').addClass('selected');
    }
    
    if ( $('body').scrollTop() > $('.section-c').position.top ) {
        $('.menu-items').removeClass('selected');
        $('.menu-c').addClass('selected');
    }
    
Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.