Fade In div when it's scrolled into viewport

馋奶兔 提交于 2019-12-03 06:12:11

Here's a solution that triggers the fadeIn jQuery function after scrolling by the .topdiv div.

It subtracts the viewport size from the scrollTop function to get the bottom of the scroll position, and then checks whether its value is greater than the height of the .topdiv div plus the 150px or however far down you'd like it to fadeIn at.

Since the div must initially be displayed on the page so that we have somewhere to scroll down to we set the visibility to hidden instead of using display:none. We're using fadeIn, which expects the element to start with display:none, so we hide the .fadethisdiv div and fade it in.

We then remove the scroll listener so that the element doesn't continuously hide and fadeIn after we have scrolled past the .fadethisdiv div.

$(window).scroll(function () {
    console.log($(window).scrollTop());
    var topDivHeight = $(".topdiv").height();
    var viewPortSize = $(window).height();

    var triggerAt = 150;
    var triggerHeight = (topDivHeight - viewPortSize) + triggerAt;

    if ($(window).scrollTop() >= triggerHeight) {
        $('.fadethisdiv').css('visibility', 'visible').hide().fadeIn();
        $(this).off('scroll');
    }
});

Fiddle

I found the library AOS very useful for this purpose (https://github.com/michalsnik/aos#-animations). Additionally to fade in when your div comes into the viewport, other effects are available. See example below

<script src="js/aos.js"></script>
<link href="css/aos.css" rel="stylesheet" />

<div id="content1" data-aos="flip-down" data-aos-delay="0">
     <p>Some content</p>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        AOS.init();
        AOS.refreshHard();  //optional
    });
</script>
dbucki

Here is solution, is set on 300px

$(document).ready(function(){
var view = {};

var checkPosition = function(){
   var elem = $('.fadethisdiv'), top = elem.offset().top;

                if (top - view.limit < 300) {
                    elem.css('display','none'); 
                }
            };

       $(window).bind('scroll', function() {

            view.top = $(window).scrollTop();
            view.limit = view.top + $(window).height();

            checkPosition();
        }); 

});

http://jsfiddle.net/kz2z5/4/

Enjoy! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!