Reputation: 3313
How to track scroll to which div position? when div height not fixed and not sure(from db select), how to make if scroll to each div then do something ...
should I store each div position push into array then if scroll position in array then scroll to key div? but this seems will be crash…..
<div class="1">1</div> // 10px height
<div class="2">2</div> // 13px height
<div class="3">3</div> // 11px height
… // … height
Upvotes: 1
Views: 513
Reputation: 5985
All elements have an offset when the DOM loads.
If you want to push all of the tops into the array, do like below. Then when your scrolling, compare the window scroll position to the arrays. If it matches an array number, do what you want with that array number. This is untested code, but the theory is there
var divTops = []; //Start an empty array
$(document).ready(function(){ //When the DOM loads
$('div').each(function(e){ //For each div
var top = $(this).offset().top; //Get its top
divTops.push(top); //and push that top into the array
});
});
$(window).scroll(function(){ //When the user scrolls
var scrolled = divTops.indexOf($(window).scrollTop()); //get the index number
if(scrolled === 0){ // Use the index number to control whatever is there.
//Do something with the first div
} else if(scrolled === 1){
//Do something with the second div
} else if(scrolled === 2){
//Do something with the third div
} else {
}
});
Upvotes: 2