2

Say I have a bunch of boxes that each contain a "scroll to top" link at the bottom. Thanks to code posted in various answers I was able to get the scrolling working pretty nicely:

<div class="box" style="height: 500px;">
    <p>some tall box</p>
    <span class="scroll-link">scroll to top of box</span>
</div>
$('.scroll-link').on('click', function () {

    var $parent = $(this).parent();
    $('html, body').animate({
        scrollTop: $parent.offset().top
    }, 'slow');

});

http://jsfiddle.net/L1d394ev/5/

However, there's one thing I still need to do, and that's where I'm stuck at: I only want to scroll if the top of the box is not visible. (Too high up to be visible, to be precise.)

I've tried the code posted in this answer - as evident in my JSfiddle if you uncomment the if - but that seems to disable the scrolling entirely.

What I guess I need to do is check if the top of the element is too high up to be visible, but how to do that, I wouldn't know.

Community
  • 1
  • 1
vvye
  • 1,208
  • 1
  • 10
  • 25

1 Answers1

4

Your problem is the way you calculate the offset:

$('.scroll-link').on('click', function () {
    var $parent = $(this).parent();
    // Get the offset alone
    var offset = $parent.offset().top;
    // If the offset is less than the scroll position
    if (offset < $(window).scrollTop()) {
        $('html, body').animate({
                      // reuse your 'offset' variable instead of calculating it again
            scrollTop: offset
        }, 'slow');
    }
});

Updated JS Fiddle Demo

blex
  • 24,941
  • 5
  • 39
  • 72
  • 2
    I could have sworn I'd tried that, but I must have screwed up somewhere. Either way, this is just what I needed - thanks a lot! – vvye Mar 15 '15 at 18:53