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++;
}
}
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.
Here is a code sample that will take you close to where you want to be:
A few things to keep in mind:
$(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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With