1

I have a product list. In the product list, scrolling shows 3 products. How can I access the 3 products that the user sees at that moment? Products have the class name product.

<div class="product">
<span>price:2</span>
</div>

<div class="product">
<span>price:2</span>
</div>
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35
  • 1
    Is your layout not responsive? It might be only one product being visible at a time, or two. – Andy Jun 07 '22 at 09:57
  • https://stackoverflow.com/questions/19669786/check-if-element-is-visible-in-dom is discussing ways to figure out whether an element is visible on the viewport. – Andy Jun 07 '22 at 09:57
  • https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API – Lee Taylor Jun 07 '22 at 23:56

1 Answers1

2

This is how you can find the item(s) that appear on the user's screen.

This is how I solved it.

<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);
              }
          }
Kevin M. Mansour
  • 2,915
  • 6
  • 18
  • 35