Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Track when user scrolls past div that is in an array

Is there a way to set an array of html elements. say Section_1, Section_2, and Section_3 are within said array. While the user scrolls down the page, and only on down-scroll, is it possible to check whether the user scrolls by sections that are specified in that array? Kinda like...

var readerLocation = 150;
var content = ['block_1', 'block_2', 'block_3'];

bottom = $(window).height() + $(window).scrollTop();
height = $(document).height();

// If user starts to scroll send an event
if (bottom > readerLocation) {
  console.log('started reading');
  var i = 0;
  for (block in content) {
    console.log(content[i]);
    //check if scrolled past element in array here()
    i++;
  }
}
like image 775
Brandon Avatar asked Dec 30 '25 20:12

Brandon


2 Answers

What you can do is set a $(window).scroll() event.

For each element in your array, you want to find its offset within the page, and compare it to your current $(window).scrollTop(). Whenever it passes say the offset().top of Section_1, then you know that it's in section 1 and has not yet reached section 2.

like image 145
David Li Avatar answered Jan 02 '26 09:01

David Li


Here is a code sample that will take you close to where you want to be:

A few things to keep in mind:

  1. Run your code by specifying your conditions within the array foreach loop.
  2. Make sure to keep track of variables rather than applying code on the fly.
  3. Since you are using jQuery, make good use of $(window).scroll to keep track of your scroll events.

$(document).ready(function(){
	var lastScrollTop = 0,
        block = ['block_2', 'block_5', 'block_7'];

	$(window).scroll(function(event){
    	var st = $(this).scrollTop(),
            block_2_offset = $('#' + block[0]).offset().top;
       	
        if (st > lastScrollTop){
            // downscroll
            block.forEach(function(block, i) {
                // check if we passed through on scroll down, then do something, modify the condition for a more specialized response
                if(st >= $('#' + content[i]).offset().top){
                    // do something
                }
            });
        }
        lastScrollTop = st;
   	});
});
div {
    padding-bottom: 500px;
    text-align: center;
}
div:nth-child(3) {
    background-color: blue;
}
div:nth-child(6) {
    background-color: yellow;
}
div:nth-child(8) {
    background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block_1">
    block 1
</div>
<div id="block_2">
    block 2
</div>
<div id="block_3">
    block 3
</div>
<div id="block_4">
    block 4
</div>
<div id="block_5">
    block 5
</div>
<div id="block_6">
    block 6
</div>
<div id="block_7">
    block 7
</div>
<div id="block_8">
    block 8
</div>
<div id="block_9">
    block 9
</div>
like image 20
AGE Avatar answered Jan 02 '26 10:01

AGE