Use jQuery to change scroll class dependent class

I have a single page site with a fixed floating navigator. I want to indicate in which section the user is included by adding the say "on" class to the corresponding navigation tag.

This class must be deleted if the user is no longer in this section, and the new current section should then be reflected in the navigator.

This cannot be done using the click function, as the user could simply scroll up and down the page. I know the idea if this can be done or where to start, since my jQuery is VERY limited.

Any help would be really appreciated.

Here is my current webpage that has no active highlighting: http://ec2.dragonstaff.com/www.creativegems.co.uk/

+3
source share
3 answers

This is similar to working with your site:

var $sections = $('section');  // all content sections
var $navs = $('nav > ul > li');  // all nav sections

var topsArray = $sections.map(function() {
    return $(this).position().top - 300;  // make array of the tops of content
}).get();                                 //   sections, with some padding to
                                          //   change the class a little sooner
var len = topsArray.length;  // quantity of total sections
var currentIndex = 0;        // current section selected

var getCurrent = function( top ) {   // take the current top position, and see which
    for( var i = 0; i < len; i++ ) {   // index should be displayed
        if( top > topsArray[i] && topsArray[i+1] && top < topsArray[i+1] ) {
            return i;
        }
    }
};

   // on scroll,  call the getCurrent() function above, and see if we are in the
   //    current displayed section. If not, add the "selected" class to the
   //    current nav, and remove it from the previous "selected" nav
$(document).scroll(function(e) {
    var scrollTop = $(this).scrollTop();
    var checkIndex = getCurrent( scrollTop );
    if( checkIndex !== currentIndex ) {
        currentIndex = checkIndex;
        $navs.eq( currentIndex ).addClass("selected").siblings(".selected").removeClass("selected");
    }
});
+9
source

You can capture the scrollTop window with

var scrollTop=$(window).scrollTop();

http://api.jquery.com/scrollTop

Then you go through the content <div>and cumulatively add your height until you get a value close enough to scrollTop. You will probably have to experiment a bit with how you handle the overlap.

Once you understand that your scrolls to the contents of, say, your portfolio, you add the appropriate class to the nav element.

0
source

:

There is a jQuery plugin called Waypoints . The implementation is pretty simple. An example on their website:

$('.thing').waypoint(function(direction) {
    alert('Top of thing hit top of viewport.');
});

So, as long as you know what is called an element, Waypoints will just be silly to implement.

0
source

Source: https://habr.com/ru/post/1768668/


All Articles