Search code examples
javascriptjqueryhtmlcssjquery-waypoints

Fade in elements with the same class only when their middle reach the viewport using jQuery waypoints


I have a one page website consisting of many sections. I would like to make it more dynamic using jQuery Waypoints.

What is should look like:

Everytime an element with class fade-in-element enters the viewport (with some offset), it gets a special class that will animate (fade) the element in - BUT ONLY the one element with the class & currently visible in the viewport.

What I have achieved:

ALL elements with the class fade in when the first element with the class enters the viewport.

HTML:

<section>Some content</section>
<section>
    <div class="container fade-in-element">
        <div class="row">
            <div class="col-sm-4"> SOME CONTENT </div>
            <div class="col-sm-4"> SOME CONTENT </div>
            <div class="col-sm-4"> SOME CONTENT </div>
        </div>
    </div>
</section>

<section>
    <div class="container fade-in-element">
        <h1 class="heading">HEADING</h1>

        <p>TEXT</p>
        <p>TEXT</p>
    </div>
</section>

CSS: .fade-in-element { opacity: 0; }

jQuery:

jQuery(document).ready(function ($) {
    $(function () {
        var inview = new Waypoint.Inview({
            element: $('.fade-in-wrap')[0],
            entered: function (direction) {
                $('.fade-in-element').addClass('animated2 fadeInLeft');
            },
            offset: '50%'
        });
    });
});

Anybody help? Thank you!


Solution

  • That's what you need

    $('.fade-in-element').each(function(){
            var _this = this;
            var inview = new Waypoint({
                element: _this,
                handler: function (direction) {
                    $(this.element).animate({'opacity': 1})
                },
                offset: '50%'
            });
    
            });
    

    This is a demo