Run javascript function when user scrolls to a spe

2020-03-03 09:23发布

I have a different function I want to run each time a user scrolls to another div or to another section of the page. Is there anyway I can do that?

2条回答
▲ chillily
2楼-- · 2020-03-03 10:11

Allready Answered here -->> Dynamic Scroll Position in Jquery

There is a great plugin to do this called WAYPOINT

I have setup an example on jsfiddle check it out

HTML

<div class="first"></div>
<div class="second"></div>

CSS

.first {
    background:green;
    height: 600px;
    width:100%;
}
.second {
    background:red;
    height: 600px;
    width:100%;
}

JS

$('.second').waypoint(function() {
    alert('You have scrolled to an entry.');
}, {
    offset: '100%'
});
查看更多
beautiful°
3楼-- · 2020-03-03 10:25

There're many ways to do this. The most simplest method:

var element = $('#my-div');

function myFunction() {
    alert('I am here!');
}

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

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

    if ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)) {
        myFunction();
    }
});

Also there're jQuery Appear plugin and Waypoints plugin:

$('#my-div').appear(function() {
    alert('I am here!');
});

$('#my-div').waypoint(function() {
    alert('I am here!');
});
查看更多
登录 后发表回答