Owen Owen - 2 years ago 270
jQuery Question

jQuery change hash (fragment identifier) while scrolling down page

I'm building a one pager website. Eg. every page (5 in total) is on one big page with the main menu fixed at the top. When you click on a menu link it slides you down to that pages anchor tag and the clicked menu item get a "active" CSS class.

What I'd like to do now is allow the user to scroll themself but still have the menu "active" item and URL hash change as they do.

So my question basically is how do I know when the user has scrolled down to a different page so I can update the menu and URL hash (fragment identifier).


Answer Source

its possible but there are a requirement to your page (for my solution to work):

your page have to be separated in divs(or sections whatever) with unique ids (i hope you dont use anchor <a>'s)

than you can use code like this:

        if (
           $(this).offset().top < window.pageYOffset + 10
//begins before top
        && $(this).offset().top + $(this).height() > window.pageYOffset + 10
//but ends in visible area
//+ 10 allows you to change hash before it hits the top border
        ) {
            window.location.hash = $(this).attr('id');

with html like this

<section id="home">
<section id="works">
<section id="about">
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download