How can JavaScript be used to dynamically load a second advertisement image immediately after the first ad image is successfully loaded?

Currently, I am working on ensuring that the 2nd ad image loads ONLY AFTER the 1st ad image has been loaded (please refer to the image with blue boxes). This is crucial as I have a CSS animation transitioning smoothly from the 1st ad image to the 2nd ad image. If the 1st ad image fails to load properly, both images will not sync accordingly.

After conducting some research, I discovered a few possible solutions. One option is to utilize cookies to store the 1st ad image and then trigger the loading of the 2nd ad image. Another approach could involve using Promises or async functions. At this point, I am uncertain about the best course of action.

https://i.sstatic.net/9hMYs.jpg

Thank you for your assistance.

Answer №1

Several posts on Stack Overflow (async/await and here) offer solutions for loading images using JavaScript and executing callbacks once loaded.

Below is a modified version of the async/await function from the first link, where the img object/element is passed directly in the resolved promise for a loaded image.

async function loadImages(urlArr) {
    // Array to hold promises
    const promiseArr = [];

    // Iterate through the URLs in the array
    urlArr.forEach(url => {
        promiseArr.push(new Promise((resolve, reject) => {
            const img = new Image();
            img.addEventListener("load", () => resolve(img));
            img.addEventListener("error", () => reject(img));
            img.src = url;
        }));
    });

    return await Promise.all(promiseArr);
}

After all images are loaded, iterate through the array of img elements returned by Promise.all().

Note that a 404 error results in a resolved promise instead of rejected. To filter out img elements with 404 responses:

const failedImages = images.filter(img => img.width <= 1);

if (failedImages.length > 0) {
    failedImages.forEach(img => {
        console.log(`The image ${img.src} failed to load.`);
    });
    return;
}

If all images load successfully, use a listener to trigger the display of the second ad image:

const transitionendListener = () => {
    sidebarAdEl.classList.add("show");
    bannerAdEl.removeEventListener("transitionend", transitionendListener);
};

bannerAdEl.addEventListener("transitionend", transitionendListener);

bannerAdEl.classList.add("show");

To see this in action, here's a sample implementation:

// Implementation code here
// CSS code here
<div class="sample">
    <p>Sample content</p>
</div>

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

transmit data via Javascript to interact with a Python web application

I'm having issues sending a json object from JavaScript to a Python webservice. The service keeps treating it as a string. Here are the codes for both client and server sides: CLIENT SIDE: $("#button").click(function () { $.ajax({ ...

How can I execute a synchronous MongoDB query in Node.js properly?

When utilizing the Node.JS driver for MongoDB, I am interested in executing a synchronous query. Here is an example of what I am aiming to achieve: function retrieveSomething() { var database = new mongo.Db("mydatabase", server, {}); database.ope ...

Extracting JavaScript variable data to PHP using Ajax technology

I've been trying to save latitude and longitude values in PHP variables, but I'm having trouble. Here is the code I'm using. Can anyone please help me figure out why these values are not being stored in PHP variables: Code: <!DOCTYPE h ...

Ui Bootstrap (angularjs) sidebar is not functioning properly

I am encountering an issue with a sidenav that I am in the process of creating for one of my projects. The goal is to develop a side menu that shifts the content to the right when opened and returns it to the left when closed, essentially functioning as a ...

Creating dynamic routes with Map in ReactJS: a beginner's guide

In the sample code below, I have added a column to the children property that includes my component. I am attempting to pass this to my Route element using map in order to dynamically populate the React Route. navLink.js export const navLinks = [ { ...

Trigger/cease cron job with the click of a button within a Node.js Express application

I have been working on a project that involves starting and stopping a cron scheduler when a user interacts with a button on the front end. Essentially, clicking the start button initiates the cron job, while clicking the stop button halts the timer. It&ap ...

What is the process of sending a file from a remote URL as a GET response in a Node.js Express application?

Situation: I am working on a Multi-tier Node.js application with Express. The front end is hosted on an Azure website, and the back end data is retrieved from Parse. I have created a GET endpoint and I want the user to be able to download a file. If the f ...

Tips on inserting javascript to modify the CSS class of a table data cell in a Flask WTF jinja2 table based on the cell's value

I have integrated Flask WTF to showcase the results of a database query. I am seeking a way to modify the cell background color to light red if the value is below 25. I am unsure about where and how to embed the JavaScript code to validate the cell value a ...

Is there a way to identify the ID of a button using Javascript specifically in Internet Explorer and Safari browsers?

Within my code, there lies a directive that contains the attribute on-blur = blurFunc($event). Imagine this scenario: I interact with a button bearing the id "myButton" located outside of the directive. How can I determine which specific button was clicke ...

Controlling the activation of a button on a parent modal popup from a child within an IFrame using javascript

I am struggling to toggle the button on the main window from the child window. Here is a snippet from the main page: <ajaxToolkit:ModalPopupExtender ID="mpeTest" runat="server" CancelControlID="btnClose" PopupControlID="pnl1" TargetControlID="showMp ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

A simple way to deactivate a React component (or the onClick event itself) using the onClick event

I have come across similar inquiries, but unfortunately, none of the solutions provided seem to work in my particular scenario. I am hopeful that someone can shed some light on what might be causing the issue. In my ReactApp, there are 3 card components t ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

Utilize the power of Request.JSON to send an HTML array as a post

I have a piece of HTML code that includes form elements: First name: <input type='text' name='first_name' value='' /><br/> Last name: <input type='text' name='last_name' value='' / ...

The requested external js scripts could not be found and resulted in a net::ERR_ABORTED 404 error

import express, { Express, Request, Response } from 'express'; const path = require("path"); import dotenv from 'dotenv'; dotenv.config(); const PORT = process.env.PORT || 5000; const app = express(); app.use(express.static(path.join ...

Firefox experiencing issues with the onchange event

Here in this block of code, I have two dropdown lists: one for department and the other for section name. Based on the selected department, I dynamically change the options available for the section name dropdown list and then populate the values from both ...

Isolating an array from an object?

I am working with a component that receives props: The data received is logged on the console. https://i.sstatic.net/F3Va4.png What is the best way to extract the array from this object? Before I pass the array to my component, it appears like this: h ...

Tips for using jQuery to create a delete functionality with a select element

I'm relatively new to utilizing jquery. I decided to tackle this project for enjoyment: http://jsbin.com/pevateli/2/ My goal is to allow users to input items, add them to a list, and then have the option to select and delete them by clicking on the t ...

Troubleshooting the non-functional asynchronous function

After starting to use redis with node (specifically the node_redis module), I decided to wrap my retrieval code for debugging and DRY principles. However, I encountered an issue where my new function wasn't working as expected. As someone who is stil ...

The task of renaming a file in javascript when it already exists by incrementing its name like file_1.txt, file_2.txt, and so on is proving to be

After trying out this code snippet, I noticed that it creates a file like file.txt as file_1.txt. However, when I try to use the same filename again, it still shows up as file_1.txt instead of incrementing the number. Is there a way to automatically incr ...