Iterating through elements with JavaScript and dynamically replacing them in the HTML code

I'm struggling with the code I found on CodePen and need some help with it since I'm not very good with JS.

  1. How can I prevent the items from repeating endlessly? Currently, they scroll indefinitely with 20 items per 'page' before the infinite scroll takes over. I would like to display 50 images in the array, 20 per page, and then stop.
  2. I want to move the JS to a separate file and use PHP to iterate over some results and display the images. Is it possible to extract the div that renders the images from the JavaScript function so that I can place them directly in the HTML block?

This is the code I have in the HTML section

<div id="SlideMiddle">
    <div id="grid">
        <div id="grid-content"></div>
    </div>
</div>

And this is the JavaScript code

<script>
    // JavaScript code goes here
</script>

Answer №1

Repetition of Images

There are two factors that contribute to the repeating behavior of images. Firstly, as mentioned in another response, the loop counter is set to a hardcoded value of 20. This means that if you input five images, each image will be repeated four times. Changing the value of 20 to the length of the Imgs array will resolve this issue.

Secondly, the function GenerateItems() always produces results.

If there are 50 images in the array, display those images, 20 per page, and then stop.

This indicates that GenerateItems() should return an empty set (or not be called) once all 50 images have been displayed. A simple approach could involve using a global page count variable. In this codepen, I have added such a variable to limit the number of pages, like so:

var pagesServed = 0;

$(document).ready(function(){ 
    $grid = $('#grid-content');
.....
function GenerateItems(){
    console.log("generating items");
    var items = '';
    if (++pagesServed > 2) {
       return items; 
    }
    for(var i=0; i < Imgs.length; i++){
      ....

Rendering on the Server Side

In a practical scenario, you would likely be fetching a list of image links from your server, which leads to the second part of your query.

You can opt to render these divs on the server side instead. The GenerateItems() function would send an AJAX request to your backend to obtain the divs, rather than constructing them in javascript. The PHP code might resemble the following:

<?php
require_once __DIR__.'/vendor/autoload.php';

session_start();

$Imgs = [
    'https://tympanus.net/Development/GridLoadingEffects/images/1.jpg',
    'https://tympanus.net/Development/GridLoadingEffects/images/3.jpg',
    'https://d13yacurqjgara.cloudfront.net/users/64706/screenshots/1167254/attachments/152315/SUGARSKULL-01.png',
    ...
];

$items = '';

for ($i=0; $i < 20; $i++){
    $items .= '<div class="grid-item c' . ($i % 9) . ' wow fadeInUp" ><a href=""><img src="' . $Imgs[$i % count($Imgs)] . '" /></a></div>';
}
...

Subsequently, GenerateItems() would look somewhat like this:

function GenerateItems(){
    console.log("generating items");
    var fetched =  fetch('http://localhost:8000').then(function(data) {
        return data.text();
    });

    return fetched;
}

And the revealItems function would be adjusted to handle the Promise:

$.fn.revealItems = function($items){
    var self = this;
    var iso = this.data('isotope');
    var itemSelector = iso.options.itemSelector;
    $items.then(function($fetcheditems) {
        console.log($fetcheditems);
        $($fetcheditems).hide();
        $(self).append($fetcheditems);
        $($fetcheditems).imagesLoaded().progress(function(imgLoad, image){
            var $item = $(image.img).parents(itemSelector);
            $item.show();
            iso.appended($item);
        });
    });
    return this;
}

I have provided an example that demonstrates rendering these divs on the server side on GitHub. Please note that this is a basic example, and certain features like the WOW styling may not be fully functional, and the CORS support is minimal.

You would need to implement your own server-side logic to determine which images to return in each request. For instance, you could utilize session management to track the images already served, or accept query string parameters specifying the range of images requested.

Answer №2

  1. When approaching the first question, my suggestion would be to modify the GenerateItems procedure

    function GenerateItems(){
        var items = '';
        var limit = Imgs.length > 20 ? 20 : Imgs.length;
        for(var i=0; i < limit; i++){
            items += '<div class="grid-item c'+(i%9)+' wow fadeInUp" ><a href=""><img src="'+Imgs[i%Imgs.length]+'" /></a></div>';
        }
        return $(items);
    }
    

Could you possibly provide a plunter or Codepen example with styling included?

  1. So if I'm understanding correctly, you'll need to specify the selector where you want the images to be generated?

a) In that case, you just need to define the function in your JS file:

function infiniteList(selector){
    $grid = $(selector);

...... }

b) Make sure to link your JS file in the header of your index.html

c) Call the function with the necessary selector in the $(document).ready section of your index.html script (place it before the closing </script> tag).

var selector = ...//perform some calculation to obtain the selector
$(document).ready(infiniteList(selector));

Answer №3

If you're looking to disable infinite scroll for the first question, here is a simple solution. You can visit this link for more information: https://codepen.io/anon/pen/mqawpy Just remember to comment out line 117 in your code.

//$(window).scroll(Infinite);

As for the second question, consider using the <?php ?> tag to insert HTML content. You can find more details on how to achieve this by visiting: How to write html code inside <?php ?>

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

Using ng-value does not trigger any updates to the Ng-model

After setting the input value Array property sum, it displays the value in the input field. However, when submitting the form, the Quantity property is not being received in the Order object. I noticed that if I change the value manually, then the Quanti ...

The ".splice()" method continuously removes the final element from an array

I have implemented a function on my form that allows me to add multiple file inputs for various images by clicking a button. Although this functionality is working correctly, I am facing an issue while trying to delete an input field using .splice. Instead ...

Creating a fixed footer within a div that is absolutely positioned using CSS

I am looking to implement a sticky footer within an absolutely positioned div element. My initial approach was to position the footer div absolutely as well - within an additional relatively positioned "page" div (which would contain the main content of t ...

Unusual situation observed in ExpressJS: Callback function fails to execute

Currently, I am facing an issue with my web app built using expressjs and node. It seems that the functionality is not working correctly. An unusual situation has occurred where accessing the first link in the browser yields the expected results, while th ...

Retrieving information from Prismic API using React Hooks

I'm having trouble querying data from the Prismic headless CMS API using React Hooks. Even though I know the data is being passed down correctly, the prismic API is returning null when I try to access it with React Hooks. Here is my current component ...

Issues with image sizing on mobile devices

After finalizing my header design, I encountered an issue with the mobile version of the website. The images in the header are not responsive and do not adapt well to different screen sizes. I need assistance converting the header design into functional co ...

Developing a jQuery Plugin to Generate an Interactive Dropdown Menu

I have a task to dynamically create a select list in which users can add options after the select list has been created. Check out my code snippet below: <script type="text/html" id="select_field"> <div class='row& ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

The alignment of the third column div is off and not displaying properly

I am having some trouble with aligning the divs on my page in a column layout. Despite setting the first two divs to float left, the third one does not align properly. I want the third div to be floated right and aligned with the first two. You can see an ...

Prevent jquery-ui datepicker from opening when the confirmation box is cancelled

Here are the snippets of code I'm currently working with: HTML, Date : <input id="datepicker"> Fare : <input id="fare"> JS, <script> $(function(){ $("#datepicker" ).datepicker({ changeMonth: true, ...

Creating a stationary div element solely with Javascript, excluding the use of CSS, jQuery, and HTML

I've been searching all day for a solution to this issue without any success. I apologize if I overlooked any relevant posts on the topic. Currently, I am working with Qualtrics and attempting to implement a textbox with scrolling instructions that fo ...

How can one achieve the equivalent of Flask Safe when making an ajax call?

Having trouble replicating equivalent functions in my Ajax call as I can in regular Javascript on my main HTML page. Using Python/Flask at the back-end. Any similar methods to use the {{ variable | safe }} syntax in AJAX for similar results? My code snipp ...

How should I start working on coding these sliders?

Which programming language should I use? My understanding of Java Script is limited, so coding them on my own might be challenging. What would be the essential code to begin with? Here are the sliders - currently just Photoshop images... ...

Adjust the scroll position in HTML by using a fixed navbar with Bootstrap 4

I am currently working on a single-page website with multiple sections. Users can navigate to these sections either by scrolling or by clicking on the navbar links. The issue I am facing is that the Bootstrap 4 navbar is fixed to the top, causing the conte ...

Exploring the depths of JSON using @attributes and @association in the realm of JavaScript and AngularJS

Currently, I am working on a project that involves utilizing an API for data retrieval, updates, and deletions. The API in question is the prestashop API. While I have managed to retrieve data and update certain items successfully, I encountered an issue. ...

Attempting to execute an SQL query in order to populate a dropdown menu by utilizing AJAX technology

Here is the code snippet I am working on: //Logic.... $companyId = $_POST['var1']; global $db; $query = "SELECT firstname, surname FROM contact WHERE directorycompany_id = " . $companyId; $result = $db->query($query); $total = $result->num ...

What steps are involved in implementing Local fonts in theme UI for Next JS?

I am currently developing an application using next JS with [theme-UI][1]. However, I need to implement local or custom fonts in my project and I'm unsure of how to do this. Below is the current theming setup: const theme = { fonts: { ...

PNG file unable to display in Google Chrome

I created an image using paint.net and saved it as a .png file. However, when I try to display the image on my website, only the borders show up without any image content. Here is the code I used: HTML <a href="home.php"><img id="logo" src="../i ...

How to toggle CSS class in Angular2/Typescript to mimic radio buttons behavior

Is there a way to create a radio button group using UL and LI elements in Angular2 and Typescript? The goal is to have all the anchors function like a radio button group where only one can be selected at a time. The selected anchor should remain "clicked" ...

Utilize the splice function when resizing the window based on specific breakpoints

On a series of div elements, I have implemented some JS/jQuery code that organizes them by wrapping every three elements in a container with the class .each-row. <div class="element"></div> <div class="element"></div> <div class ...