10

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?

k0pernikus
  • 60,309
  • 67
  • 216
  • 347

3 Answers3

16

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();

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 2
    Got three downvotes on that, but a simple setInterval like that does not use much resources and works just fine, but should have some sort of ending if the class was never found, like a timeout function that clears the interval after a couple of seconds. The jQuery funcion for listening to DOM node inserted is probably the best way to do it, but unless the handler is removed that will just keep on going, checking all inserted elements for the className, which in my opinion is worse than having a setInterval. – adeneo Apr 26 '12 at 14:13
3

You could trigger some event once you added the class.

Example:

$('#ele').addClass('theClass');
$(document).trigger('classGiven')


$(document).bind('classGiven',function(){
    //do what you need
});
Braden Steffaniak
  • 2,053
  • 3
  • 25
  • 37
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
0

I'm sorry if I got your question wrong but why not just doing something plain as this on document.ready ? :

$("#myelement").addClass('myclass');

if($("#myelement").hasClass('myclass')) {
    alert('do stuff here');
}
kernelpanic
  • 2,876
  • 3
  • 34
  • 58
  • 1
    I do not add the element with this class. It gets added by another script. And I want to catch that change and afterwards do some magic on it. – k0pernikus Apr 26 '12 at 13:59
  • so maybe better would be add callback in that another script if possible? – Vytautas Apr 26 '12 at 14:05