Steven Palinkas Steven Palinkas - 2 months ago 6
Javascript Question

jQuery.ready() equivalent event listener on elements?

I am using jQuery JavaScript library.
I like the event listener ready on

that fires when the DOM is set up.

( Pretty similar to .onload )

I would find it very useful, if there was an event listener wich has a very similar behaviour to this, but fires when an element is fully loaded. (f.e.: Picture, a Div, such )

I would appreciate both jQuery or JavaScript methods.


jQuery don't have it, but we can create our own onDomElementIsReady, Tools: jQuery, ES6, Promise and Interval (I'm lazy, but you can get the idea)

We will wait until the element existed on the DOM and as soon is available we will resolve the promise result.

  const onDomElementIsReady = (elementToWatch)=> {
    //create promise
    return new Promise((res, rej)=> {
      let idInterval = setInterval(()=> {
        //keep waiting until the element exist
        if($(elementToWatch).length > 0) {
          clearInterval(idInterval); //remove the interval
          res($(elementToWatch)); //resolve the promise             

//how to use it?
onDomElementIsReady(".myElement").then(element => { 
                          //use jQuery element

NOTE: To improve this we should add a timer that reject the promise if the DOM element never exists.