This is the method to locate the item(s) displayed on the user's screen.
This is my approach to the issue.
<div class="product" itemData='{"itemId":"SK-GKHNGNS1"}'>
<span>price:2</span>
</div>
<div class="product" itemData='{"itemId":"SK-TRK"}'>
<span>price:2</span>
</div>
$(document).ready(function(){
let oldScroll = 300;
findItems();
$(window).scroll(function() {
if (oldScroll < (parseInt(window.pageYOffset) - 200) || oldScroll > (parseInt(window.pageYOffset) + 200)) {
console.log(oldScroll);
oldScroll = window.pageYOffset;
findItems();
}
});
});
function findItems() {
var i = 0;
var visibleProducts = [];
$(". product").each(function (index) {
if ($(this).hasClass('pushItem')) {
return true;
}
var start = window.pageYOffset;
var end = window.pageYOffset + window.innerHeight;
var productPositionStart = $(this).position().top;
var productPositionEnd = productPositionStart + (($(this).height() / 3) * 2);
if (start <= productPositionStart && end >= productPositionEnd) {
$(this).addClass('pushItem')
visibleProducts.push($.parseJSON($(this).find('a').attr('itemData')));
i++;
}
});
if (visibleProducts.length > 0) {
console.log(visibleProducts);
}
}