animated scroll on same page links

by gvee

HTML

<div id="content">
    <div class="section" id="section1">section 1 content</div>
    <div class="section" id="section2">section 2 content</div>
    <div class="section" id="section3">section 3 content</div>
</div>
<ul id="menu">
    <li> <a href="#section1">Section 1</a>

    </li>
    <li> <a href="#section2">Section 2</a>

    </li>
    <li> <a href="#section3">Section 3</a>

    </li>
</ul>

CSS

* {
    margin: 0;
    border: 0;
    padding:0;
}
#menu {
    position: fixed;
    list-style-type: none;
    right: 10px;
    top: 20%;
    width: 100px;
}
#menu .highlighted {
    background-color: yellow;
}
#content {
    margin-right: 120px;
}
#section1 {
    background-color: red;
    height: 400px;
}
#section2 {
    background-color: blue;
    height: 200px;
}
#section3 {
    background-color: green;
    height: 800px;
}

JavaScript

$('a[href*=#]').click(function (e) {
    e.preventDefault();

    var id = $(this).attr('href');
    var scrollTo = $(id).offset().top;

    $('html,body').animate({
        'scrollTop': scrollTo
    }, 500);
});

$(document).scroll(function () {
    highlightSection();
});

function highlightSection() {
    // Where's the scroll at?
    var currentPosition = $(this).scrollTop();

    // Remove highlights from all
    $('a[href*=#]').removeClass('highlighted');

    // Loop over each section
    $('#content .section').each(function () {
        // Calculate the start and end position of the section
        var sectionStart = $(this).offset().top;
        var sectionEnd = sectionStart + $(this).height();

        // If the current scroll lies between the start and the end of this section
        if (currentPosition >= sectionStart  && currentPosition < sectionEnd) {
            // Highlight the corresponding anchors
            $('a[href=#' + $(this).attr('id') + ']').addClass('highlighted');
        }
    });
};

highlightSection();