Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run javascript function when user scrolls to a specific div [duplicate]

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?

like image 755
kduan Avatar asked Jan 11 '23 13:01

kduan


2 Answers

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%'
});
like image 172
Vikas Ghodke Avatar answered Jan 27 '23 02:01

Vikas Ghodke


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!');
});
like image 22
emerkulova Avatar answered Jan 27 '23 02:01

emerkulova