jQuery change each element with class when it comes into view

时间:2017-05-16 09:40:11

标签: javascript jquery

I have a series of blocks that repeat like this:

<div class="producto_banner">
    <div class="positioner">
        <div class="left">
            <div class="titulo">Title</div>
            <div class="subtitulo">Subtitle</div>
            <div class="introduccion">Intro</div>
            <a class="boton" href="#">anchor</a>
        </div>
        <div class="right">
            <img src="image source">
        </div>
    </div>
</div>

<div class="producto_banner">
    <div class="positioner">
        <div class="left">
            <div class="titulo">Title</div>
            <div class="subtitulo">Subtitle</div>
            <div class="introduccion">Intro</div>
            <a class="boton" href="#">anchor</a>
        </div>
        <div class="right">
            <img src="image source">
        </div>
    </div>
</div>

...

And I would like to animate the .right div inside each of them when they come into view.

So far I have this:

function isScrolledIntoView(elem) {
    var centerY = Math.max(0,((jQuery(window).height()-
jQuery(elem).outerHeight()) / 2) 
              + jQuery(window).scrollTop());

    var elementTop = jQuery(elem).offset().top;
    var elementBottom = elementTop + jQuery(elem).height();

    return elementTop <= centerY && elementBottom >= centerY;
}

$(window).on("scroll resize", function() {
    console.log('scrolling');
    $(".producto_banner").each(function(index, element) {
        if (isScrolledIntoView(element)) {
            $(this).find('.right').animate({'right':'50px'},1000);
        }
   });
});

But for some reason it’s only animating the last 2 blocks (out of 5)

0 个答案:

没有答案