Instructions on how to send HTML content as a string to a different function for iteration?

Encountering an issue where a function is returning JSON data upon success. Attempting to implement infinite scroll functionality, the function prepares HTML for looping in another function. The server response includes JSON structured as follows:

{ "id" : 6,
  "title" : "Store Title #1",
  "movies" : [{ "id" : 1164,
                "title" : "Movie 1",
                "publishDate" : "1993-01-01T00:00:00",
                "description" : "{long description...}" },
              { "id" : 8452,
                "title" : "Movie 2",
                "publishDate" : "1985-01-01T00:00:00",
                "description" : "{long description...}" },
              { "id" : 6451,
                "title" : "Movie 3",
                "publishDate" : "1945-01-01T00:00:00",
                "description" : "{long description...}" }]
}

Function that handles success:

     function onsuccess(data) {
        var libraryInfoHTML = '<h2 data-id="' + data.id + '">' + data.title + '</h2><ul></ul>';
        var receivedData = data.movies;
        var loopHTML = 
            '<li>' +
                '<h3 class="clear"><span class="icons video-library video-icon"></span>' +
                    '<a href="#" title="' + receivedData[i].title + '" data-id="' + receivedData[i].id + '">' +
                        receivedData[i].title +
                    '</a>' +
                '</h3>' +
                '<h4 class="clear"><span class="icons publish-date"></span>' +
                    receivedData[i].publishDate +
                '</h4>' +
                '<p>' +
                    receivedData[i].description +
                '</p>' +
            '</li>';
    infinityScroll(receivedData, loopHTML);
}

Infinite scroll function:

function infinityScroll(received_data, loop_HTML) {
    var i=0;
    var length = received_data.length;
    var items_to_load = 10;
    function loop() {
        var html_maker = '';
        for(; i<items_to_load; i++) {
            html_maker +=
              loop_HTML;
        }
        items_to_load += i;
        $('#container ul').append(html_maker);
    }

    function scroller() {
        if ($(window).scrollTop() >= ($(document).height() - $(window).height())*0.95){
            loop();
        }
    }
    $(window).scroll(scroller);
}

The error arises in the first function due to "i" being undefined. Looking to pass the content of "loopHTML" to "function loop()" and iterate over "receivedData[i]". Considering converting the "loopHTML" content to a string but unsure how to handle unstring locations for "receivedData[i]". Seeking suggestions on a better approach without plugins for implementing simple infinite scroll. Thank you in advance!

Answer №1

If you are looking to implement a function in infinityScroll that handles the received data and utilizes the parameter i, consider passing a function like this:

 function onsuccess(data) {
     var libraryInfoHTML = '<h2 data-id="' + data.id + '">' + data.title + '</h2><ul></ul>';

     var htmlFunction = (function () {
         var receivedData = data.movies;
         return function (i) {
             if (i < receivedData.length) {
                 return '<li>' +
                     '<h3 class="clear"><span class="icons video-library video-icon"></span>' +
                     '<a href="#" title="' + receivedData[i].title + '" data-id="' + receivedData[i].id + '">' + receivedData[i].title +
                     '</a>' +
                     '</h3>' +
                     '<h4 class="clear"><span class="icons publish-date"></span>' + receivedData[i].publishDate +
                     '</h4>' +
                     '<p>' + receivedData[i].description +
                     '</p>' +
                     '</li>';
             }
         };
     })();
     infinityScroll(htmlFunction);
 }

You will also need to make adjustments to the infinityScroll function...

function infinityScroll(loopHtmlFunction) {
    var items_to_load = 10;
    var i = 0;
    var html;
    function loop() {
        var html_maker = '';
        for(; i<items_to_load && html = loopHtmlFunction(i); i++) {
            html_maker += html;
        }
        items_to_load += i;
        $('#container ul').append(html_maker);
    }    
    // etc.
}

Keep in mind, this approach ensures that the function checks for additional movie data in receivedData before appending it to the HTML. Consider modifying other parts of the infinityScroll function to end the scrolling process when there is no more movie data available.

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

On mobile devices, the height of the absolutely positioned element is larger than its

I currently have an element with a background image that includes an absolutely positioned element at the bottom. As the screen width decreases, the height of the absolutely positioned element increases and surpasses the parent element. Since absolutely p ...

utilizing staggered animations with three.js

I am trying to animate an array of meshes in Three.js, but the properties are not being recognized. tl.staggerFrom(array, 2, {"position.y":-100}) The position.y doesn't change. When I use console.log(array[0].position.y), it gives me the initial val ...

Using Python with Selenium to Execute JavaScript Code

Struggling to gather data from a website that relies heavily on JavaScript is proving to be quite challenging, especially since I lack knowledge of JavaScript. Here's what I've managed to put together so far: from selenium import webdriver fro ...

When using Codeigniter and AJAX to delete an item from a table, the page unexpectedly becomes

I successfully integrated ajax into my pagination and search functionality, which appears to be working well. However, I encountered an issue when attempting to refresh the list after deleting an item - the page would simply return blank. I am seeking guid ...

What is the best way to implement the "setTimeOut" function using React hooks?

I am struggling with showing a "notification" on the component based on the server response, and I want that notification to disappear after 5 seconds. I've tried using setTimeout but haven't had any success. Can anyone provide assistance? Below ...

Timing measurements in JavaScript: comparing Date.now with process.hrtime

I need to regularly calculate the time difference between specific time intervals. When it comes to performance, which method is more efficient: Date.now or process.hrtime? C:\Windows\system32>node > process.hrtime() [ 70350, 524700467 ] ...

Tips for employing multiple reducers with subscribe in Redux (Request for Comments)?

I am trying to utilize data from two reducers on a single page while using combine reducers. However, I encountered the following error: Attempted import error: 'cartItemsReducer' is not exported from './cartItemsReducer'. Attempted i ...

Sending a Json object back to an Ajax request made to a webMethod

I have been working on implementing an Ajax call method and an ASP.NET web method. The ASP.NET function I created is returning some values that I need to handle in the Ajax call. Despite trying various approaches, I have not yet succeeded in achieving th ...

Using JSF components `h:inputFile` and `f:ajax` for file input

I'm feeling a bit confused. I wanted to create a simple example where we can upload a file from an XHTML page and display something.jpg while the file is being uploaded. Here's what I did: <h:outputScript library="javascript" name="showProgre ...

Tips for changing the size and color of SVG images in a NextJS application

Looking to customize the color and size of an svg image named "headset.svg". Prior to this, I used next/image: <Image src={'/headset.svg'} alt='logo' width={30} height={30} className='object-contain' /> The s ...

Transferring the values of JavaScript objects to HTML as strings

My goal is to generate HTML elements based on the values of specific JavaScript objects that are not global variables. However, when attempting to execute the code below, I encounter an error stating "params is not defined." What I actually aim to achieve ...

How can I use a specific condition to query for a particular element in an $in array in MongoDB?

Although I am skeptical that this is achievable, I will give it a shot here. Below are some examples of records in the database: { type: 'fruit', name: 'apple', quantity: 3 } { type: 'fruit', name: ' ...

What is the best way to continuously execute the ajax request for downloading a pdf file?

if( $.isArray(certTypeReq) ){ $.each(certTypeReq,function(key,certType){ $.ajax({ url: baseUrl+"/user/certificate/getlink", type: 'GET', data: { 'certType' : certType}, ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

What is causing the error when trying to parse a JSON with multiple properties?

Snippet: let data = JSON.parse('{"name":"dibya","company":"wipro"}'); Error Message : An error occurred while trying to parse the JSON data. The console displays "Uncaught SyntaxError: Unexpected end of JSON input" at line 1, character 6. ...

Is NodeJS Asynchronous: Has the callback been called twice?

I'm currently working with the Async module in Node.JS to manage my asynchronous calls. However, I've encountered an issue stating "Callback already called." Could someone assist me with resolving this problem? async.each(data['results&apos ...

Explanation of the role of `::` in Angular Formly

My goal is to master working with Angular, but I'm struggling to grasp some of the syntax used in the guides and examples on the official website. In one example for defining a button form control, I came across this template: <div><button t ...

Issue with React useCallback not recognizing changes in dependencies caused by child functions

Can anyone lend a hand with this issue? I would greatly appreciate it. I've looked through previous questions but couldn't find anything quite like my situation. Here's the gist of it: I have a useCallback react hook that generates a set o ...

"Improprove your website's user experience by implementing Material UI Autocomplete with the

Recently, I experimented with the Autocomplete feature in Material UI. The focus was on adding an option when entering a new value. You can check out the demo by clicking on this link: https://codesandbox.io/s/material-demo-forked-lgeju?file=/demo.js One t ...

Error encountered with the NextGen (Mirth) Connect and MongoDB Java driver connection

I'm currently in the process of setting up Mirth Connect Server 3.10.1 (Java version: 1.8.0_181) to write FHIR JSON documents to MongoDB. Following the instructions provided in this post, I have included the following drivers in my custom-lib/ directo ...