0

I have a bunch of divs with class .container scattered across my page. I want to trigger an animation with jquery when I have scrolled to a .container but I want the animation to be only on that div.

$('.container').waypoint(function(direction){
    $this = $(this);
    $(function(){
        //$this here selects the last div with class .container
    });
},{offset: 'bottom-in-view'});

How can I select only the current div I've scrolled to?

1 Answers1

1

Edit

Sorry, I misunderstood you. The code below should allow one to detect when one of your containers comes into view via the scroll event.

'use strict';

$(function() {
    var containers = $('.container');

    function isScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }

    window.onscroll = function (event) {
        for (var i = 0; i < containers.length; i++) {
            var container = containers[i];
            if (isScrolledIntoView(container)) {
                // animate as needed here
                console.log('you can see' + container.innerHTML);
            }
        }
    };
});

The isScrolledIntoViewfunction was shameless lifted from here.

Community
  • 1
  • 1
m.casey
  • 2,449
  • 13
  • 10