简体   繁体   中英

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!

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

You should wrap it inside an if. You can check the window size with $(window).width and .height., and the current position with $(document).scrollTop. You can set up a bounding box with these values and check if the div is inside.

var top = $(document).scrollTop();
var height = $(window).height();
$('.fade-in-wrap').each(function(){
    var off = $(this).offset();
    if(off.top > top && off.top < top+height) {
        // Add the waypoint here. The element must be $(this)!
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM