0

I would like to animate a div when user scrolls the page.

For that, i implemented this code:

var slide = jQuery(".apresentacao-spc-01");
var opening = false;
var closing = false;
var pos = jQuery(window).scrollTop();
jQuery(window).scroll(function() {
    var pos = jQuery(window).scrollTop();
    console.log(pos);
    if (pos > 100) {

        if (!opening) {

            opening = true; closing = false;
            slide.stop().animate({
                'opacity': 1,
                'margin-left': '0px'
            }, 700, function() {
                opening = false;
            });

        }


    } else {
        if (!closing) {
            closing = true; opening = false;
            slide.stop().animate({
                'opacity': 0,
                'margin-left': '-1000px'
            }, 500, function() {
                closing = false;
            });

        }
    }
});

The issue is: Using "if (pos > 100) {", if the user resolution is big enough to show the element before he needs to scroll, he won't see the element unless he begins to scroll the page.

My question is: How can I get a scroll animation that will be executed when the element is visible?

I mean: If the element is visible on page load, the animation automatically starts... If the element is not visible on page load, the animation waits the scroll reach the element to start...

Thanks.

Flávio Alencar
  • 137
  • 2
  • 8

1 Answers1

0

There a few different things you could do. My first thought was to query the height of the viewport with something like this:

var viewportWidth  = document.documentElement.clientWidth
, viewportHeight = document.documentElement.clientHeight

And then trigger the animation if it is taller than the distance the element is down.

A more dynamic solution would be to use a function that checks to see if the element is in viewport the automatically, that way you wouldn't need to worry about adjusting the height if you changed stuff on your page:

function isElementInViewport (el) {
var rect = el.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() */
);
}

credit to this response. There is a use guide and further information in the link provided. Good luck!

Community
  • 1
  • 1
BenJamin
  • 773
  • 4
  • 15