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.