Locate items visible to the user on the display

I need to find a way to access the products that are currently visible when a user scrolls through my product list. Each product in the list has the class name product.

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

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

Answer №1

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);
              }
          }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Double trouble: Knockout validation errors displayed twice

Currently, I am using the knockout validation plugin to validate a basic form field. The validation functionality is working as expected, however, it seems to be displaying the same error message twice under the text box. The code snippet that I am using ...

The session in Express.js is not retained across different domains

I am currently developing a third-party application that will be utilized across multiple domains. My main goal is to manage a session per user who uses the app, which led me to implement the express-session module for this purpose. However, I encountered ...

Direct users from one path to another in Express framework

I have two main routes set up in nodejs. First is the users.js route: router.post('/users/login', function(request, response) { // Logic for user login // Redirect to dashboard in dashboard.js file after login response.redirect(&ap ...

Utilize Mongoose's post method to generate a fresh collection without any data

Libraries in use: Express, Mongoose, Express-Restify-Mongoose Challenge: I am currently exploring the process of creating a POST request that involves providing the schema within the req.body. My goal is to seamlessly generate a new collection if it doesn ...

The webpack production build consistently displays the message "This site is running on the development build of React."

I have been attempting to utilize webpack-4 for generating a production build of my React project (not built with Create React App), but I am facing difficulties. The project is written in TypeScript and uses ts-loader, as well as React version 15.6.2. Be ...

Using a JavaScript function to post the input value and then displaying it through PHP

I am striving to create an input field that will capture the value of what is typed and display it. The JavaScript function is designed to retrieve the value of the input box two seconds after the user stops typing and then post it. However, the issue lies ...

List component in Angular not refreshing after sorting the array in the service

Currently, I am delving into the realm of Angular (version 5+) to enhance my skills by working on a small project. The project involves setting up basic routing functionalities to showcase the ContactList component upon selecting a navigation tab. Addition ...

Creating a tooltip for new list items: A step-by-step guide

I'm currently working on creating a tooltip using JQuery for incoming list items. Users will input text in a textfield, press enter, and those values will be displayed in a visible list on the website. I intend to have a tooltip associated with each i ...

The AJAX POST request encountered an error

I apologize for the lackluster title. Basically, when the script is executed, it triggers an 'error' alert as shown in the jQuery code below. I suspect that the issue lies in the structure of my JSON data, but I'm uncertain about the necess ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

encountering a problem with npm while trying to execute the project

Encountering a persistent issue when attempting to run my project with npm start, even after downgrading my node version. Despite trying various solutions found on platforms like stackoverflow and stackexchange, such as deleting the node_modules folder, ru ...

Ways to identify when text wraps to the next line

I'm working on a navigation menu (.navigation) that I want to hide instead of wrapping onto the next line when the screen width is small. I've been trying to figure out how to use javascript/jQuery to detect when wrapping occurs and hide the navi ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Utilizing AJAX to amplify the worth of plupload's echo capabilities

Greetings! Here is the JavaScript code I am using for plupload var uploader = new plupload.Uploader({ runtimes : 'html5,flash,silverlight,html4', browse_button : 'pickfiles', // you can pass in id... container: document.getElementById( ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Customize footer data in ui-grid design

I'm having trouble formatting the aggregate value for a column in ui-grid. Currently, the number display looks like this: total: 6370.046074130321 but I would prefer it to be formatted like this: total: $6370.05 I've attempted using both of ...

Tips on showing binary information as images using extjs 4

As the proud owner of a valid .JPEG image's binary data, I am on a quest to convert this information into an actual viewable image using Python. Seeking advice on how to successfully transform this binary code into a visually appealing .JPEG format w ...

The table element fails to display in IE11 due to a rendering issue, displaying the error message: "Render error - TypeError: Object does not support the property or method 'entries'"

As someone new to web app development, I am currently working on a project that involves using Vue cli and antd components, with the additional challenge of ensuring compatibility with IE11. However, I have encountered an issue where IE11 does not render ...

I am trying to map through an array fetched from Firebase, but despite the array not being empty, nothing is displaying on the

I retrieved an array of products from a firebase database using the traditional method: export const getUsersProducts = async uid => { const UsersProducts = [] await db.collection('products').where("userID", "==", uid).get().then(sn ...