Posted By

shengyongjiang on 01/09/14


Tagged

jquery


Versions (?)

Wait until an dom element exists


 / Published in: JavaScript
 

URL: http://stackoverflow.com/questions/5525071/how-to-wait-until-an-element-exists

$(selector).waitUntilExists(function);

  1. function ($) {
  2.  
  3. /**
  4. * @function
  5. * @property {object} jQuery plugin which runs handler function once specified element is inserted into the DOM
  6. * @param {function} handler A function to execute at the time when the element is inserted
  7. * @param {bool} shouldRunHandlerOnce Optional: if true, handler is unbound after its first invocation
  8. * @example $(selector).waitUntilExists(function);
  9. */
  10.  
  11. $.fn.waitUntilExists = function (handler, shouldRunHandlerOnce, isChild) {
  12. var found = 'found';
  13. var $this = $(this.selector);
  14. var $elements = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);
  15.  
  16. if (!isChild)
  17. {
  18. (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
  19. window.setInterval(function () { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 500)
  20. ;
  21. }
  22. else if (shouldRunHandlerOnce && $elements.length)
  23. {
  24. window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
  25. }
  26.  
  27. return $this;
  28. }
  29.  
  30. }(jQuery));

Report this snippet  

You need to login to post a comment.