0

There is an empty popup div already loaded in the page. When the user click on an image, a div is created and sent into the popup. I'm looking for an event to listen to the end of the appendChild:

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();
        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, the event load doesn't seem to work with appendchild. What kind of event is usable after an appendchild?
PS: Everything works fine until popup.addEventListener function

EDIT:
The MutationObserver function is surely the best option, but I went to the setTimeout alternative to keep my code shorter and simpler for the small function needed.
I'll learn the MutationObserver soon for future development.

Tritof
  • 159
  • 7
  • 2
    Maybe you are looking for something like a [MutationObserver](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) – VLAZ Jun 10 '19 at 15:05
  • 1
    Possible duplicate of [Detect changes in the DOM](https://stackoverflow.com/questions/3219758/detect-changes-in-the-dom) – ponury-kostek Jun 10 '19 at 15:10

1 Answers1

1

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

Probably you need to call a function simply after the popup is shown.
In that case, try to use window.setTimeout().

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

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();
        popup = document.createElement("div");
        popup.innerHTML = galerieImages[i].nextElementSibling.innerHTML;
        galeriePopup.appendChild(popup);
        setTimeout(onPopupLoaded, 0);
    })
};

The timing of appendChild completion is after returned to event loop.
i.e., after end of the click event listener function.
Calling setTimeout() with delay 0, the callback function onPopupLoaded() will be executed as soon as possible after drawing process.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

Takashi Harano
  • 294
  • 1
  • 3
  • 10