Skip to content

Instantly share code, notes, and snippets.

@khrome
Created December 19, 2011 07:44
Show Gist options
  • Save khrome/1495937 to your computer and use it in GitHub Desktop.
Save khrome/1495937 to your computer and use it in GitHub Desktop.
String.whenInDOM : call a function on a DOM element from the future
if(!String.whenInDOM){
if(!String.defaultReplacementTimeout)
String.defaultReplacementTimeout = 16384;
String.implement({
whenInDOM : function(
callback,
delayCallback,
timeoutCallback,
timeout,
counter
){
if(!timeout) timeout = String.defaultReplacementTimeout;
if(!counter) counter = 0;
if(!timeoutCallback) timeoutCallback = function(event){
throw(
'Element did not appear in DOM(\''+event.id+
'\') after '+event.time+'ms'
);
};
if(!document.id(this)){
// we want to get the DOM node when it appears
// so we're looking for a gradient falloff of intervals
// as it approaches timeout
var delayTime = Math.pow(2, counter);
if(delayTime >= timeout){
timeoutCallback({
id : this,
count : counter,
time : delayTime
});
}
counter++;
this.whenInDOM.delay(delayTime, this,
[callback, delayCallback, timeoutCallback, timeout, counter]
);
if(delayCallback) delayCallback({
count : counter,
time : delayTime
});
}else{
callback(document.id(this));
}
}
});
}
'my_awesome_id'.whenInDOM(function(){
//do stuff here
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment