Guest User

Untitled

a guest
Apr 30th, 2016
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. ;(function ($, window) {
  2.  
  3. var intervals = {};
  4. var removeListener = function(selector) {
  5.  
  6. if (intervals[selector]) {
  7.  
  8. window.clearInterval(intervals[selector]);
  9. intervals[selector] = null;
  10. }
  11. };
  12. var found = 'waitUntilExists.found';
  13.  
  14. /**
  15. * @function
  16. * @property {object} jQuery plugin which runs handler function once specified
  17. * element is inserted into the DOM
  18. * @param {function|string} handler
  19. * A function to execute at the time when the element is inserted or
  20. * string "remove" to remove the listener from the given selector
  21. * @param {bool} shouldRunHandlerOnce
  22. * Optional: if true, handler is unbound after its first invocation
  23. * @example jQuery(selector).waitUntilExists(function);
  24. */
  25.  
  26. $.fn.waitUntilExists = function(handler, shouldRunHandlerOnce, isChild) {
  27.  
  28. var selector = this.selector;
  29. var $this = $(selector);
  30. var $elements = $this.not(function() { return $(this).data(found); });
  31.  
  32. if (handler === 'remove') {
  33.  
  34. // Hijack and remove interval immediately if the code requests
  35. removeListener(selector);
  36. }
  37. else {
  38.  
  39. // Run the handler on all found elements and mark as found
  40. $elements.each(handler).data(found, true);
  41.  
  42. if (shouldRunHandlerOnce && $this.length) {
  43.  
  44. // Element was found, implying the handler already ran for all
  45. // matched elements
  46. removeListener(selector);
  47. }
  48. else if (!isChild) {
  49.  
  50. // If this is a recurring search or if the target has not yet been
  51. // found, create an interval to continue searching for the target
  52. intervals[selector] = window.setInterval(function () {
  53.  
  54. $this.waitUntilExists(handler, shouldRunHandlerOnce, true);
  55. }, 500);
  56. }
  57. }
  58.  
  59. return $this;
  60. };
  61.  
  62. }(jQuery, window));
Add Comment
Please, Sign In to add comment