Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until HTML elements gets a class then do something

I am waiting for the document.ready event in order to do something on my page.

Alas some other script, which I cannot change, has not worked its magic yet once my script is called. Hence, jquery selection on the class name fails as the class does not yet exist in the DOM.

This is why I want tell my function to listen until an element gets a certain class, then do something with it.

How do I achieve this?

like image 660
k0pernikus Avatar asked Apr 26 '12 13:04

k0pernikus


1 Answers

Something like this (pseudo code) :

var timer = setInterval(function() {
   if (element.className=='someclass') {
       //run some other function 
       goDoMyStuff();
       clearInterval(timer);
   }
}, 200);

or listen for the element to be inserted:

function flagInsertedElement(event) {
   var el=event.target;
}
document.addEventListener('DOMNodeInserted', flagInsertedElement, false);

jQuery version:

$(document).on('DOMNodeInserted', function(e) {
    if (e.target.className=='someclass') { 
        goDoMyStuff();
    }
});

There's also the liveQuery plugin:

$("#future_element").livequery(function(){
    //element created
});

Or if this is a regular event handler, delegated events with jQuery's on();

like image 192
adeneo Avatar answered Nov 15 '22 16:11

adeneo