user2907241
user2907241

Reputation: 265

Make JS detect position on page?

I got a one-page website, before that it had 3 different pages, and the navigation bar's link to the current page turned to ´id="selected´

#selected {
background-color:white;
color: #645406;
cursor: default;
}

when you are on that page. Now it's a bit harder, as the links work just as anchor links. I'd need a script that would detect where the user is scrolling, and automatically turn the anchor's link to ´id="selected"´ when the user scrolls over the anchor.

Example: http://jsfiddle.net/mbSXB/

Upvotes: 0

Views: 78

Answers (1)

akrasman
akrasman

Reputation: 83

Try this http://jsfiddle.net/8NKqf/1/

$(function() {
    var anchors = $('.anchor');
    var navLinks = $('.navigointi a');

    $(window).scroll(function() {
        var scrollTop    = $(window).scrollTop();
        var clientHeight = document.documentElement.clientHeight;
        var activeSectionAnchor, hash;

        anchors.each(function() {
            if ($(this).offset().top < scrollTop + clientHeight) {
                activeSectionAnchor = $(this);
            }
        });

        hash = "#" + activeSectionAnchor.attr('name');

        activeLink = navLinks.removeClass('selected').filter('[href="' + hash + '"]');

        activeLink.addClass('selected');
    });
});

Upvotes: 1

Related Questions