Becky
Becky

Reputation: 2289

How to get an animation to start once in viewport

I have a page that uses the fullpage.js plugin. This plugin allows the user to scroll down and an entire 100%vh screen to appear.

My issue is that I have animations on different sections that I want to delay until that div is within the viewport. It took me a while to figure this out and was trying to do scroll functions, forgetting that fact I am not really scrolling. Before I was trying to do this:

<div id="section1-right-container">
    <div id="think"></div>
</div>


$(window).on("scroll", function(){
        // Determine if the element is in the viewport
        if($('section1-right-container').visible(true)) {
        $('section1-right-container').addClass("think");
    }
});

I found the following code and modified it some, I am just unsure of how to elimate the scrolling part and to start the animation once the section1-right-container is in the viewport.

// Returns true if the specified element has been scrolled into the viewport. /*function isElementInViewport(elem) { var $elem = $(elem);

    // Get the scroll position of the page.
    var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
    var viewportTop = $(scrollElem).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    // Get the position of the element on the page.
    var elemTop = Math.round( $elem.offset().top );
    var elemBottom = elemTop + $elem.height();

    return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}

// Check if it's time to start the animation.
/*function checkAnimation() {
    var $elem = $('#think');

    // If the animation has already been started
    if ($elem.hasClass('start')) return;

    if (isElementInViewport($elem)) {
        // Start the animation
        $elem.addClass('start');
    }
}

Anyone know what I could do?

UPDATE - visible plugin

(function(e) {
  e.fn.visible = function(t, n, r) {
    var i = e(this).eq(0),
      s = i.get(0),
      o = e(window),
      u = o.scrollTop(),
      a = u + o.height(),
      f = o.scrollLeft(),
      l = f + o.width(),
      c = i.offset().top,
      h = c + i.height(),
      p = i.offset().left,
      d = p + i.width(),
      v = t === true ? h : c,
      m = t === true ? c : h,
      g = t === true ? d : p,
      y = t === true ? p : d,
      b = n === true ? s.offsetWidth * s.offsetHeight : true,
      r = r ? r : "both";
    if (r === "both") return !!b && m <= a && v >= u && y <= l && g >= f;
    else if (r === "vertical") return !!b && m <= a && v >= u;
    else if (r === "horizontal") return !!b && y <= l && g >= f
  }
})(jQuery)

Upvotes: 0

Views: 569

Answers (1)

Alvaro
Alvaro

Reputation: 41595

Why don't you make use of the fullPage.js callbacks such as onLeave or afterLoad?

That's the purpose of them.

Upvotes: 1

Related Questions