After appending a child, is there a specific event listener that can be utilized?

An empty popup div is already displayed on the page. When a user clicks on an image, a new div is created and inserted into the popup. I am searching for an event that can detect when the appendChild operation is completed:

let galerieImages = document.getElementsByClassName("field-galerie-image");
let galeriePopup = document.getElementById("galerie-popup");
for(let i = 0; i < galerieImages.length; i++) {
    galerieImages[i].addEventListener("click", function(e) {
        e.preventDefault();
        let popup = document.createElement("div");
        popup.innerHTML = galerieImages[i].nextElementSibling.innerHTML;
        galeriePopup.appendChild(popup);
       popup.addEventListener("load", function(e) {
          console.log("popup loaded");
    })
};

In this code snippet, it appears that the load event does not work effectively with the appendChild method. Are there any other events that can be used after appending a child element?
PS: All functionalities are functioning correctly until the point of defining popup.addEventListener.

EDIT:
Using the MutationObserver function could be a more suitable option, but I opted for the setTimeout alternative to maintain simplicity and conciseness in my code for this specific requirement.
I plan to explore the MutationObserver feature in the near future for further enhancements.

Answer №1

When a page is loaded, the "load" event is only fired once.
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event

If you need to execute a function right after a popup is displayed, consider using window.setTimeout().

function onPopupLoaded() {
    console.log("popup loaded");
}

let galleryImages = document.getElementsByClassName("field-galerie-image");
let galleryPopup = document.getElementById("galerie-popup");
for(let i = 0; i < galleryImages.length; i++) {
    galleryImages[i].addEventListener("click", function(e) {
        e.preventDefault();
        popup = document.createElement("div");
        popup.innerHTML = galleryImages[i].nextElementSibling.innerHTML;
        galleryPopup.appendChild(popup);
        setTimeout(onPopupLoaded, 0);
    })
};

The appendChild operation completes after returning to the event loop,
meaning it occurs after the click event listener function ends.
By utilizing setTimeout() with a delay of 0, the callback function onPopupLoaded() will be executed as soon as possible after the rendering process.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

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

Managing images in JavaScript while conserving memory

Welcome I am embarking on a project to construct a webpage using HTML, CSS, JavaScript (jQuery), and nearly 1000 images. The length of the HTML page is substantial, around 5000px. My vision involves creating a captivating visual experience for users as t ...

Using Ajax to fetch project data from an API

Currently immersed in a personal coding project, I'm struggling to troubleshoot my code. Essentially, I need to retrieve data from an API and display it on my HTML page. The data type is "jsonp" due to CORS errors that required this workaround for de ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Having trouble reading the file using jQuery in Internet Explorer 8 and earlier versions due to its non-XML format (albeit resembling XML)

Currently, I am utilizing AJAX to load a KML file (which essentially functions as an XML file). The parsing works seamlessly in IE9, FF, and other browsers, but encounters issues in IE8. Although the data is retrieved, I face difficulties parsing it in jQu ...

Encountering a problem with routing in multiple user dashboards on React Js

My application has different types of users, each with specific access rights. To ensure data is rendered correctly based on user permissions, I have filtered my API queries accordingly. As a beginner in React, I felt it was necessary to separate the sideb ...

Tips for choosing the default first option in a select box or dropdown menu

I'm having trouble displaying a select box using a directive. The default option is not showing up. This is what I have: <div> <select ng-init="userselected = vm.data[0]" ng-model="userselected" ng-options="optio ...

Adding and removing DateFields in Django formsets dynamically

I am encountering a unique issue specifically related to the django-bootstrap-datepicker-plus package. Within my Todo list application, I am aiming to enable tasks to appear on multiple specific dates. I have successfully set up my model, configured my fo ...

Looking for tips on how to achieve a sleek search bar expansion effect when focusing using w3.css?

I have been trying to utilize the following code to create a Google search bar that expands when focused within a w3.css navigation bar-item. While it does expand and contract on focus/blur, I am unable to achieve smooth transitions between sizes. The sear ...

Tips for extracting certain characters from a URL and saving them as an ID using JavaScript

Consider this scenario where I have a specific URL: http://localhost:3000/legone/survey/surveyform/form11/03141800300000030001 In order to achieve the desired outcome, I aim to extract and store different parts of the URL into designated IDs. Specificall ...

I seem to be having trouble getting Vue to recognize my components. Could it be that I am not registering them

I am currently working on developing a simple blog application using Laravel with Vue.js. I have successfully created custom components, registered them in my app.js file, and referenced them in the views by their component names. However, upon loading the ...

Unable to retrieve the numerical value within the chart

I am a beginner in learning angularjs. I have implemented a contextmenu for displaying table data. <div contextmenu-container="meta.contextmenu"> <table class="table table-striped table-bordered report-table" fixed-header> ...

Stripping the prefix from a string using the .split function leads to an error message stating "Unexpected

When dealing with a string containing a unique prefix, I attempted to separate it into an array after the backslash character "\" by using the split function. Here is the string: i:0#.w|itun\allepage_fg This was my approach: function claimOrder ...

"Is it possible to selectively load only a few images on a website that contains numerous

My website displays numerous images hosted on a server. Each page contains a maximum of 100 images, each within its own div element. At any given moment, only one div is visible due to the CSS "display" property, while the others are hidden using display:n ...

What is the best way to properly save a pdf and docx file in React JS?

My challenge is to efficiently download a docx or pdf file in React JS (based on server response) once the server responds. The backend is written in Python/Flask. Although the file downloads successfully, it appears corrupted and damaged when I try to op ...

establish expiration date for image

On my e-commerce site, users upload images to customize product items, such as adding their photo to a cake. I'm curious if there's a way to automatically delete these images after a certain expiry date. Is it possible to implement an automatic ...

Steps to display a variable in JavaScript on an HTML textarea

I'm working on a JavaScript variable called 'signature' var signature; //(Data is here) document.write(signature) Within my HTML document, I have the following: <div id="siggen"> <textarea id="content" cols="80" rows="10">& ...

Unable to utilize jQuery within the NetBeans IDE

Whenever I try to include a jQuery file in Netbeans like this: <script type="text/javascript" src="js/jquery-1.3.2.js"> my code doesn't seem to work. However, when I use the following method: <script type="text/javascript" src="http://ajax ...

Can you explain the distinction between 'rxjs/operators' and 'rxjs/internal/operators'?

When working on an Angular project, I often need to import functionalities like the Observable or switchMap operator. In such cases, there are two options available: import { switchMap } from 'rxjs/operators'; or import { switchMap } from ' ...

Steps for transforming an index into a value within an Object

const arr = [{ "name": "Toyota" }, { "name": "Renault" }, { "name": "Jeep" }] const array_unique = (arr) => Array.from(new Set(arr)); const car = array_unique( arr.map((item) => item.name), ).sort(); console.log(car); // => ['Toyota ...

Should the use of readFileSync() during the initialization of a Node.js web application be avoided?

I have a Node app that serves web pages with static HTML-snippet files included conditionally. I am considering implementing a cache map for these snippets by adding the following code to my Express's app.js file: var cache = Object.create(null); cac ...