2

I got this code bit from another Stack Overflow question, but there seems to be a minor problem. The hash changes correctly as I move from section to section, but when I try to scroll back up, it jumps to the very top instead of a smooth manual scrolling. Any help would be appreciated :)

HTML

<!doctype html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="script.js"></script>
</head>
<header>
</header>
<body>
    <div class="main">
        <section id="one" class="section"></section>
        <section id="two" class="section"></section>
        <section id="three" class="section"></section>
        <section id="four" class="section"></section>
        <section id="five" class="section"></section>
        <section id="six" class="section"></section>
    </div>
</body>
</html>

And here is the JS:

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

2 Answers2

1

instead of pageYOffset you can do $(window).scrollTop() which will return the top of the page offset distance from the top of the document in the window. If you wish to animate the scroll to the property you will want to scroll to the position of the element with the id. If you wish to animate scrolling to the top of the page you can do

$(window).animate({
  top: 0
}, 1000);
CWitty
  • 4,269
  • 3
  • 20
  • 34
0

you can overcome this problem by adding a scroll up animation in javascript, in this way we add delay to the scroll, which gives perfect effect of scroll to top.

Javascript

window.onload = function() {
// short timeout
setTimeout(function() {
    $(document.body).scrollTop(0);
    }, 15);
};
Marmik Bhatt
  • 597
  • 3
  • 15