Is the removal of an element from the array happening prematurely?

I am currently working on implementing a basic lazy loading functionality for images. The idea is to process an array of images and remove each image from the array once it has been loaded.

Below is the code I have written:

  const removeFromArray = (id) => {
    const position = images.indexOf(id);

    if (id.classList.contains(classes.loaded)) {
      images.splice(id, 1);
    }
  }

  const setHeight = (img, target) => {
    const parentWidth = img.parentNode.offsetWidth;
    const initw = target.width;
    const inith = target.height;

    return (parentWidth / initw) * inith;
  }

  const loadImage = (img) => {
    const image = new Image();

    img.classList.add(classes.loading);
    image.src = img.getAttribute('data-lazy-img');
    image.onload = function(e) {
      const target = e.target || e.srcElement;

      img.style.height = `${setHeight(img, target)}px`;
      img.classList.add(classes.loaded);
      img.classList.remove(classes.loading);
      img.src = img.getAttribute('data-lazy-img');

      removeFromArray(img);
    }
  }

The issue I am facing is that sometimes the incorrect image is removed from the array, especially when removing the later ones.

You can view my entire code here: http://codepen.io/tomekbuszewski/pen/LbRQxq?editors=0011

What steps should I take to address this problem?

Answer №1

Using an image id as a parameter for the splice function doesn't seem logical:

 images.splice(id, 1);

Perhaps you intended to use the position instead:

 images.splice(position, 1);

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

How to eliminate the ng-component tag from an Angular 8 table row template

I currently have a dynamic table component with 2 modes: Normal table - functioning properly Custom Row Template - encountering issues due to Angular adding the <ng-component> tag The logic within the TableComponent is not the main concern, it&apo ...

Expanding file input fields in Javascript

I am facing an issue with my form and file input. I need to select images from a different folder. echo '<pre>'; var_dump($_FILES); echo '</pre>'; Upon submitting the form, only the last selected image is displayed, but I ...

Is it possible to utilize WebRTC (simple-peer) with STUN without the need for additional signaling?

I am currently exploring the utilization of the simple-peer library to create browser-to-browser WebRTC connections through data channels. My understanding, although it may be flawed, is that for two browsers to establish a connection via WebRTC, they need ...

Label alignment in one line with responsive checkbox

Could someone assist me with adjusting the alignment of this checkbox when resizing the window for mobile view? The label text is breaking into a new line while the checkbox remains in its original position. How can I make the checkbox align closer to its ...

What are your thoughts on using a click function within the same tag as an ngFor directive in Angular and JavaScript?

There is a table with a row element called tr. Should the `Click` event use the same tag as the `*ngFor` directive? If this is not recommended, how can I enhance the code? ...

Upload a JSON file to a server using a JavaScript app

I am in the process of creating a basic JavaScript application that allows users to annotate images stored on their machine and save these annotations as a JSON file. This application is lightweight and straightforward, not requiring an app server. Howeve ...

Accessing and modifying the HTML content of a specific <td> element within a specified <tr> row

Thank you for the assistance with my previous question - it was very helpful. However, I have encountered a new issue. I am able to automatically refresh my "Table" every 5 seconds with the following code: function GetStatus() { $.ajax({ url: ...

Interacting between React and Express with CKEditor 5: How to send a request

import React, { Component, useState, useEffect } from 'react'; import { CKEditor } from '@ckeditor/ckeditor5-react'; import ClassicEditor from '@ckeditor/ckeditor5-build-classic'; import axios from 'axios'; import pa ...

Determining the navigation changes within a React browser

Hi there, I'm using browserHistory.goForward() and browserHistory.goBack() to navigate forward and backward in my app with arrow buttons. However, I need a way to determine if the route has actually changed after executing browserHistory.goForward/goB ...

Error encountered when trying to generate a collection from JSON using Backbone framework

jQuery(function() { var Hotel = Backbone.Model.extend({ defaults: { idHotel:"", hotelName:"Grand Marina", hotelAddress:"Lakeview Drive", hotelStars:"4", hotelRoomsCount:"180", ...

retrieving a URL with the help of $.getJSON and effectively parsing its contents

I seem to be struggling with a coding issue and I can't quite figure out what's wrong. My code fetches a URL that returns JSON, but the function is not returning the expected string: function getit() { var ws_url = 'example.com/test.js&ap ...

delayed updating of property not visible in angular 10 immediately

I needed to hide a div based on a condition, so I decided to use the hidden property like below: <div [hidden]="isControlDisplayed()?false:true"> The isControlDisplayed() method determines whether to show or hide the div based on the value ...

Animating all the numbers on a jQuery countdown timer

http://jsfiddle.net/GNrUM/ The linked jsfiddle showcases a countdown of 2 seconds, with only the numbers displayed. My goal was to explore: a) How can I incorporate animations into the JavaScript code so that the number changes in size, color, and positi ...

Display tables side by side using Material-UI

Presently, I am utilizing NextJs and MaterialUI to display a table with data fetched from an API created in Strapi. Challenge The current issue lies in using a table component with props that are imported into a page, where the props are mapped to an API ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

Rails is capable of responding to URLs with ajax crawling enabled

The google guide Explaining AJAX Applications Crawling explains how to structure your URL with a hash and ! to ensure your site is crawlable. An excellent example of this is the revamped Twitter. For instance, if you enter the URL: http://twitter.com/dini ...

React-Redux Countdown Timer Component

I recently created a JavaScript function in Symfony, but now I need to transfer it to React-Redux. However, as a beginner in React, I am struggling to make it work. Here is the issue I am facing: In my application, there is a list of cars parked in a par ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

Is it possible to retrieve a callback function from a select event in the Bootstrap dual listbox?

I'm fairly new to front-end development and have been using the Bootstrap DualListbox for a project. I'm looking for a way to save items moved from one list to another to a database before they are officially transferred. Is there a callback func ...