Using jQuery, we can replace all `<span>` elements with `<img>` elements and then verify if the images have been successfully loaded

Similar Inquiry:
jQuery check if image is loaded

I find myself in a scenario where the following HTML structure is utilized:

<div class="image">
    <img class="" src="content-images/1.jpg">
    <span class="slide" rel="content-images/2.jpg"></span>
    <span class="slide" rel="content-images/3.jpg"></span>
    <span class="slide" rel="content-images/4.jpg"></span>
</div>

All children of div.image are absolutely positioned in the CSS, causing them to overlap each other.

My objective is to switch the span elements with img ones and set their src attribute to the value specified in the rel attribute within each span. These images are large and high resolution, so they may take some time to load completely.

Using JavaScript or jQuery, I need to display a loading message or indicator from when a button is clicked elsewhere on the page until all the span elements have been replaced with img elements and finished loading.

Due to issues with images and caching, using jQuery's .load() method is not feasible in this case.

While attempting to use imagesloaded, it did not provide the functionality I require.

Are there any alternative methods you can suggest to achieve this task?

Answer №1

Not entirely certain if this is the exact solution you're looking for, but it's worth a shot...

$("#button").click(function(){
    console.log("Loading initiated...");
    // Identify all spans to be replaced and count them
    var imgSpans = $("div.image span.slide"), 
        toLoad = imgSpans.length,
        loaded = 0;
    // Initiate loading for each image
    for (var i = 0; i < toLoad; ++i) {
        // Use closure to maintain correct value of i
        (function(i){
            // Preload image
            var img = new Image();
            img.src = imgSpans.eq(i).attr("rel");
            img.onload = function(){
                // Upon completion of loading, replace span with image...
                imgSpans.eq(i).replaceWith(img);
                if (++loaded == toLoad) {
                    // ...and check if all images have been loaded at this point
                    console.log("Loading completed...");
                }
            };
        })(i);
    }
});

DEMO (JSFiddle)

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

When attempting to add an item to an array within a sub-document using Mongoose and MongoDB, the error message "Property 'messages' not found" is returned

I am working with four different models: teacher, student, teacherMessageSchema, and studentMessageSchema. The teacherMessageSchema is a subdocument within the 'teacher' model under the messages: [teacherMessageSchema] property, while the student ...

Tips for maintaining accessibility to data while concealing input information

Is it possible to access data submitted in a form even if the inputs were hidden by setting their display to none? If not, what approach should be taken to ensure that data can still be sent via form and accessed when the inputs are hidden? ...

Enhance your HTML5 video by incorporating strategically placed buttons (images) as an overlay

Recently, I embedded a video: <video preload muted autoplay loop id="sty"> <source src="content/1/sty.mp4" type="video/mp4"> </video> To make this video full-width, I made sure to set the CSS properti ...

What is the best way to incorporate a countdown timer on an ASP.NET webpage?

Looking to display a countdown timer in the top right corner of my ASP page that starts from 00:00:30 and counts down to 00:00:00 before resetting back to 00:00:30. Does anyone have any suggestions on how to achieve this? ...

Invalid PDF File - Unable to Complete Download via $http

I'm facing an issue while attempting to download a PDF file using the $http service in AngularJS. Upon trying to open the downloaded file, I encounter an error message stating "Invalid Color Space" and the page appears blank. To troubleshoot this pr ...

The unique identifier for a specific child element in Firefox

While working on this website: I customized the right sidebar navigation using: .sidenav a:after { display: block; position: relative; z-index: 0; top: -3.6em; left: 0.15em; width: 90%; content: "."; font-family: 'R ...

Utilize React to process and submit payments through Stripe

I am currently working on integrating Stripe Elements with my React application. The JavaScript page below showcases the code I use to submit the payment form, which I have compiled from various sources online. Upon submitting the form, I receive a token; ...

Refresh the Express Server following the file upload

This is a simple express server setup that includes file uploading and reading functionality. const express = require("express") const fileUpload = require("express-fileupload") const cors = require("cors") const morgan = require("morgan") const fs = requi ...

What is the best way to personalize the collector for each individual?

Currently, I have a bot that is capable of collecting messages and replying if it detects a specific word. However, I am facing an issue where the bot keeps creating new collectors every time someone types the word tekong. As a result, the bot ends up resp ...

Leveraging $.ajax() for sending a POST request to a PHP file hosted on a different domain

Is it possible to use $.ajax() for sending a POST request to a PHP file on another domain? I encountered an error message with $.ajax(). It works fine in Chrome or Firefox and sends emails, but in IE, the email is not sent. This is an HTML file <form ...

Steering clear of using relative paths for requiring modules in Node.js

When it comes to importing dependencies, I like to avoid using excessive relative filesystem navigation such as ../../../foo/bar. In my experience with front-end development, I have found that using RequireJS allows me to set a default base path for "abso ...

Efficiently loading data using lazy loading in jsTree

I have been facing a challenge with dynamically loading the nodes of a jtree upon expansion. The limited documentation I could find is located towards the end of this specific page. Several solutions involve creating nodes individually using a loop, simil ...

Tips for testing a mapbox popup using jasmine testing?

I encountered an issue with my mapbox popup while using jasmine and attempting to write a unit test for it. Here is the function in question: selectCluster(event: MouseEvent, feature: any) { event.stopPropagation(); this.selectedCluster = {geo ...

Tips on invoking a mixin within a Jade template showcased in a Node/Express endpoint

I'm currently developing a component that I plan to use multiple times on a website through a Jade template. This is how my route is set up: router.get('/', function(req, res, next) { res.render('indicators',{category:"", num ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

Having trouble retrieving values for jVectorMap? The getElementById method doesn't seem to be functioning as

I have been trying to set markers on a jVectormap. I retrieve the content from my database and store it in a hidden input field. The format of the data is as follows: {latLng:[52.5200066,13.404954],name:'Berlin'},{latLng:[53.0792962,8.8016937],n ...

Attach the footer to the bottom of the screen only if the main page text is limited in length

How can I ensure that my footer sticks to the bottom of the screen only when there is minimal content on the page? When there is a lot of content, I'd like the footer to appear after the content rather than being pinned at the bottom, especially since ...

How about this: "Effortlessly upload files by simply dragging and dropping them from your computer to

Currently, I am facing a challenge in uploading a picture from my PC to a website that utilizes a drag and drop interface. Despite using Javascript to open the required link, set properties, and click on the upload field, a file manager window appears wh ...

"encountered net::ERR_NAME_NOT_RESOLVED error when trying to upload image to s3 storage

I am currently developing an application using Angular. I have been attempting to upload a picture to my S3 bucket, but each time I try, I encounter this error in the console. https://i.stack.imgur.com/qn3AD.png Below is the code snippet from my upload.s ...

Revoke the prior invocation of the Google Maps geocoding function

While working on implementing an autocomplete with JavaScript and the Google Maps geocode method (using the keyup event on input), I have encountered a problem where I sometimes receive the results of the previous search instead of the current one. I am l ...