0

I found this: How to tell if a DOM element is visible in the current viewport?.

When I put it in my JS and force a scroll, it is not reporting the correct information.

function inViewport(e) {

//special bonus for those using jQuery
if (e instanceof jQuery) {
    e = e[0];
}

var rect = e.getBoundingClientRect();

return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
     );
}

$('html,body').animate({
    scrollTop: $("#8").offset().top
});

var divsVisible = [];
$('div[id]').each(function() {
if (inViewport(this)) {
    divsVisible.push( this.id );
}
});     

debug.log(divsVisible);

My HTML file is here: https://dl.dropboxusercontent.com/u/163931/index.html

I would expect the array to have '8' in it. Instead it has '1' in it. Mac/Safari.

Community
  • 1
  • 1
emd
  • 434
  • 1
  • 7
  • 18
  • What happens if you call the `inViewport` function **after** the animation? Right now you are calling it **before** the animation is complete. – Felix Kling Jun 25 '14 at 04:34
  • How do I call it after? I'm new to jquery and don't quite have it all figured out. – emd Jun 25 '14 at 05:03
  • Pass a complete callback to `.animate` and put your code inside the callback: https://api.jquery.com/animate/#animate-properties-duration-easing-complete . Also see https://learn.jquery.com/effects/custom-effects/ – Felix Kling Jun 25 '14 at 05:04
  • So it doesn't do statements in order then? How do I ensure order? I will try that tomorrow when I'm back in front of computer. Thanks for your help. – emd Jun 25 '14 at 05:13
  • `.animate` kicks of an asynchronous process, which is only started *after* the current execution terminates. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop. You ensure order by passing a callback to `.animate`. The callback is executed when the animation finished. – Felix Kling Jun 25 '14 at 05:14
  • I tried this code: `$('html,body').animate({ scrollTop: $("#8").offset().top, complete: function() { alert('in'); } });` and the alert is not fired. – emd Jun 27 '14 at 18:00
  • That's because you are not using the API correctly. Have a look at the documentation again: https://api.jquery.com/animate/#animate-properties-duration-easing-complete. Just pass the function as second argument to `.animate`. – Felix Kling Jun 27 '14 at 19:48
  • @FelixKling: thanks! Not sure why my options/properties way wasn't working but I got it firing now. If you know anything about Scrollfire: http://stackoverflow.com/questions/24399378/jquery-plugin-scrollfire-not-firing-properly – emd Jun 27 '14 at 20:08

0 Answers0