Home > Software design >  JS : How to get notified after insertBefore()?
JS : How to get notified after insertBefore()?

Time:10-30

Is there a way to get notified, after inserting an element into the DOM with insertBefore(), when this element becomes actually visible/available to user ? Especially to start applying CSS transforms on it ?

Complete problem

Forgive me if this question is recurrent, I didn't find a suitable answer so far. I'm trying to implement a custom popup dialog system on a website of my own, similar to SweetAlert or some other products.

I would like to apply some special effects when this popup shows up, such as a progressive darkening of the background, as well as a slow vertical motion on the box itself.

To achieve all of this, I spawn one big, fixed div element covering the whole screen (the background) and containing the popup box. When I need it, I first insert this element as body's first child, tagging it with a special invisible class. Once inserted, I remove this invisible class from the element and let the CSS rules do the magic.

The problem is that even if removed the class after having inserted this element, this one will be rendered only when the Javascript function leaves, hence directly in its final state.

When doing this on a complete initial page, the load event helps. I now would like to do the same on an existing page.

As always, I'm interested on both solutions to this (potentially XY) problem: if there's a better way to do it, I'll be happy to discover it, but I'm still interested in solving this particular situation anyway.

Thanks in advance to everyone.

EDIT: currently performing tests on Firefox 82.0.2

CodePudding user response:

Thanks to comments above, here's a valid solution to both exposed problems:

  • "Mutation Observer", as well as former "Mutation Events" (now deprecated) are the best way to get notified when something is inserted. It won't help with animations issues, though, because it's still not guaranteed to be rendered yet at this time ;
  • Rather than applying a class then another to perform a transition, it's better to define a regular animation using @keyframes that plays only once. It's guaranteed to be played when the object appears, by definition.

Many thanks to "Pomax", F4st3r and epascarello for their help.

  • Related