waiting for a DOM element to become available

Public

Warning message

We recommend you to assign at least one category to this snippet so you could easily navigate it in the future. Edit your snippet here.

waiting for a DOM element to become available

Get raw version
javascript
  1. // http://forum.jquery.com/topic/waiting-for-a-dom-element-to-become-available#14737000002248405
  2. $.fn.onAvailable = function(fn){
  3. var sel = this.selector;
  4. var timer;
  5. var self = this;
  6. if (this.length > 0) {
  7. fn.call(this);
  8. }
  9. else {
  10. timer = setInterval(function(){
  11. if ($(sel).length > 0) {
  12. fn.call($(sel));
  13. clearInterval(timer);
  14. }
  15. },50);
  16. }
  17. };
  18. $("#demo span").onAvailable(function(){
  19. alert("Available!!");
  20. $(this).addClass('foo');
  21. });
  22. setTimeout(function(){
  23. $("#demo").append("<span>foobar</span>");
  24. },5000);