Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS execute function if element is loaded - no jQuery

I have an div with an id of doi, and I want to manipulate it with JavaScript when it is fully loaded (the manipulation uses the dimensions of the images which is not provided in the DOM).

What I tried:

document.getElementById('doi').onload = function(){
        console.log('Div of Interest is loaded');
    };

This didn't work because the division was probably loaded before I set the Event Handler. So for short, what needs to be done is the following:

  • Check if the element is loaded
    • if so? -> fire callback function
    • if not? -> set an event handler with callback when fully loaded.
like image 477
Nicky Smits Avatar asked Nov 02 '22 01:11

Nicky Smits


2 Answers

Pure javascript: jsFiddle Demo Using jQuery: jsFiddle Demo

(The demos include some setup which is just filler to show changing content)

To expand on the notion (only in rare cases) of using timers to monitor an element's contents. The content to be observed would more than likely be a combination of its text, html, width, and height. Here is one way to monitor those:

javascript

function monitor(element,callback){
 var self = element;
 var h = self.clientHeight;
 var w = self.clientWidth;
 var txt = self.innerText;
 var html = self.innerHTML;
 (function flux(){
    setTimeout(function(){
        var done = 
          h == self.clientHeight &&
          w == self.clientWidth &&
          txt == self.innerText &&
          html == self.innerHTML;
        if( done ){
         callback();
        }else{
         h = self.clientHeight;
         w = self.clientWidth;
         txt = self.innerText;
         html = self.innerHTML;
         flux();
        }
    },250);
 })()
};

jQuery extension

$.fn.monitor = function cb(callback){
 var set = this.first();
 var h = set.height();
 var w = set.width();
 var txt = set.text();
 var html = set.html();
 (function flux(){
    setTimeout(function(){
        var done = 
          h == set.height() &&
          w == set.width() &&
          txt == set.text() &&
          html == set.html();
        if( done ){
         if( $.isFunction(callback) )callback();
        }else{
         h = set.height();
         w = set.width();
         txt = set.text();
         html = set.html();
         flux();
        }
    },500);
 })()
};
like image 109
Travis J Avatar answered Nov 12 '22 16:11

Travis J


For an image, you can check its width property. If it's non-zero, then the image has either loaded, or at least loaded enough that its dimensions are known.

like image 43
Niet the Dark Absol Avatar answered Nov 12 '22 17:11

Niet the Dark Absol