-1

Here is an example http://jsfiddle.net/pwk0vvuo/

<div id="wrapper" style="height:100px; width:100%;">
    <div id="header" style="height:300px; width:100%;"></div>
</div>

When I make the first scroll down, I'd like if the page could jump the entire header. An then when I scroll up, I'd like if, as soon as the header appears on screen, the scroll jumps to the top of the page (showing the entire header).

marco
  • 1,152
  • 1
  • 9
  • 20

2 Answers2

0

You can simply check your position and if you are scrolling with jQuery. So you can do something like this:

Edited:

var lastScrollTop = 0;
var firstScrollDown = true;
var scrollUp = false;
$(window).scroll(function (event) {
    var st = $(this).scrollTop();
    if (st > $('#content').offset().top) {
        scrollUp = true;
    }
    if (st > lastScrollTop) {
        if ($(window).scrollTop() !== 0 && firstScrollDown) {
            firstScrollDown = false;
            $('html, body').animate({
                scrollTop: $('#content').offset().top
            }, 'slow');
        }
    } else {
        if ($(window).scrollTop() < $('#content').offset().top && scrollUp) {
            $('html, body').animate({
                scrollTop: $('#header').offset().top
            }, 'slow');
            scrollUp = false;
        }
    }

    lastScrollTop = st;
});

http://jsfiddle.net/4n6mer0y/1/

  • your solution is interesting but It works only on the first scroll down and and it does not work on scroll up. Following [this solution](http://stackoverflow.com/questions/4326845/how-can-i-determine-the-direction-of-a-jquery-scroll-event) I tried [this script](http://jsfiddle.net/pwk0vvuo/13/). It works and seems to be ok but it has a bug: when you scroll down and then immediately wcroll up the animation goes in loop. – marco Oct 25 '14 at 21:23
  • edited your code so it does not get caught in the loop. http://jsfiddle.net/4n6mer0y/1/ – davidtrautmann Oct 26 '14 at 09:27
0

If not a complete solution, than pretty close

   var lastScrollTop = 0;
    $(window).scroll(function () {

        if ($('#header').scrollTop() + $('#header').innerHeight() >= $(window).scrollTop()) {
            var st = $(this).scrollTop();
            if (st > lastScrollTop) {
                console.log('scroll down');
                $('html, body').animate({
                    scrollTop: $('#header').scrollTop() + $('#header').innerHeight()
                }, 2000, function() {
                    $('html, body').stop();
                });
            } else {
                console.log('scroll up');
                $('html, body').animate({
                    scrollTop: $('#header').scrollTop()
                }, 2000, function() {
                    $('html, body').stop();
                });
            }
        }
        lastScrollTop = st;
    });
Master Slave
  • 27,771
  • 4
  • 57
  • 55