jquery.attrchange.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. /*
  2. A simple jQuery function that can add listeners on attribute change.
  3. http://meetselva.github.io/attrchange/
  4. About License:
  5. Copyright (C) 2013 Selvakumar Arumugam
  6. You may use attrchange plugin under the terms of the MIT Licese.
  7. https://github.com/meetselva/attrchange/blob/master/MIT-License.txt
  8. attrchange is a simple jQuery function to bind a listener function to any HTML element on attribute change.
  9. DEMOS & DOCUMENTATION:
  10. ======================
  11. http://meetselva.github.com/attrchange/
  12. Reference:
  13. ==========
  14. - http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
  15. - https://developer.mozilla.org/en/DOM/Mutation_events
  16. - https://developer.mozilla.org/en/DOM/DOM_Mutation_Observers
  17. - http://msdn.microsoft.com/en-us/library/ie/ms536956%28v=vs.85%29.aspx
  18. Browser Support Information:
  19. ============================
  20. This plugin has been successfully tested in the following browsers:
  21. IE6+
  22. FF
  23. Chrome
  24. `DOMAttrModified` - Supported in IE 9, FF and Opera
  25. `MutationObservers` - is very new and it is supported in FF and Chrome 18.
  26. `onpropertychange` - Only in IE
  27. Known Issues:
  28. ============
  29. attrchange plugin uses different API to support cross browser/backward compatibility.
  30. The response has been normalized to match with the response from MutationObserver however
  31. the return values from the API's are sometimes different especially on style attribute.
  32. On changing the style attribute, Older standard such as DOMAttrModified/onpropertychange
  33. returns the specific css property that was updated (ex: return for updating css top would return -> top: 60px)
  34. but the MutationObserver returns the entire style attribute value and not the property that was changed
  35. (something like $(this).attr('style')).
  36. Example:
  37. ========
  38. <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  39. <script type="text/javascript"
  40. src="https://raw.github.com/meetselva/attrchange/master/attrchange.js"></script>
  41. <script type="text/javascript">
  42. $(selector).attrchange({
  43. trackValues: true, // Default to false, if set to true the event object is updated with old and new value.
  44. callback: function (event) {
  45. //event - event object
  46. //event.attributeName - Name of the attribute modified
  47. //event.oldValue - Previous value of the modified attribute
  48. //event.newValue - New value of the modified attribute
  49. //Triggered when the selected elements attribute is added/updated/removed
  50. }
  51. });
  52. </script>
  53. */
  54. (function($) {
  55. function isDOMAttrModifiedSupported() {
  56. var p = document.createElement('p');
  57. var flag = false;
  58. if (p.addEventListener) p.addEventListener('DOMAttrModified', function() {
  59. flag = true
  60. }, false);
  61. else if (p.attachEvent) p.attachEvent('onDOMAttrModified', function() {
  62. flag = true
  63. });
  64. else return false;
  65. p.setAttribute('id', 'target');
  66. return flag;
  67. }
  68. function checkAttributes(chkAttr, e) {
  69. if (chkAttr) {
  70. var attributes = this.data('attr-old-value');
  71. if (e.attributeName.indexOf('style') >= 0) {
  72. if (!attributes['style']) attributes['style'] = {}; //initialize
  73. var keys = e.attributeName.split('.');
  74. e.attributeName = keys[0];
  75. e.oldValue = attributes['style'][keys[1]]; //old value
  76. e.newValue = keys[1] + ':' + this.prop("style")[$.camelCase(keys[1])]; //new value
  77. attributes['style'][keys[1]] = e.newValue;
  78. } else {
  79. e.oldValue = attributes[e.attributeName];
  80. e.newValue = this.attr(e.attributeName);
  81. attributes[e.attributeName] = e.newValue;
  82. }
  83. this.data('attr-old-value', attributes); //update the old value object
  84. }
  85. }
  86. //initialize Mutation Observer
  87. var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
  88. $.fn.attrchange = function(o) {
  89. var cfg = {
  90. trackValues: false,
  91. callback: $.noop
  92. };
  93. //for backward compatibility
  94. if (typeof o === "function" ) {
  95. cfg.callback = o;
  96. } else {
  97. $.extend(cfg, o);
  98. }
  99. if (cfg.trackValues) { //get attributes old value
  100. $(this).each(function (i, el) {
  101. var attributes = {};
  102. for (var attr, i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
  103. attr = attrs.item(i);
  104. attributes[attr.nodeName] = attr.value;
  105. }
  106. $(this).data('attr-old-value', attributes);
  107. });
  108. }
  109. if (MutationObserver) { //Modern Browsers supporting MutationObserver
  110. /*
  111. Mutation Observer is still new and not supported by all browsers.
  112. http://lists.w3.org/Archives/Public/public-webapps/2011JulSep/1622.html
  113. */
  114. var mOptions = {
  115. subtree: false,
  116. attributes: true,
  117. attributeOldValue: cfg.trackValues
  118. };
  119. var observer = new MutationObserver(function(mutations) {
  120. mutations.forEach(function(e) {
  121. var _this = e.target;
  122. //get new value if trackValues is true
  123. if (cfg.trackValues) {
  124. /**
  125. * @KNOWN_ISSUE: The new value is buggy for STYLE attribute as we don't have
  126. * any additional information on which style is getting updated.
  127. * */
  128. e.newValue = $(_this).attr(e.attributeName);
  129. }
  130. cfg.callback.call(_this, e);
  131. });
  132. });
  133. return this.each(function() {
  134. observer.observe(this, mOptions);
  135. });
  136. } else if (isDOMAttrModifiedSupported()) { //Opera
  137. //Good old Mutation Events but the performance is no good
  138. //http://hacks.mozilla.org/2012/05/dom-mutationobserver-reacting-to-dom-changes-without-killing-browser-performance/
  139. return this.on('DOMAttrModified', function(event) {
  140. if (event.originalEvent) event = event.originalEvent; //jQuery normalization is not required for us
  141. event.attributeName = event.attrName; //property names to be consistent with MutationObserver
  142. event.oldValue = event.prevValue; //property names to be consistent with MutationObserver
  143. cfg.callback.call(this, event);
  144. });
  145. } else if ('onpropertychange' in document.body) { //works only in IE
  146. return this.on('propertychange', function(e) {
  147. e.attributeName = window.event.propertyName;
  148. //to set the attr old value
  149. checkAttributes.call($(this), cfg.trackValues , e);
  150. cfg.callback.call(this, e);
  151. });
  152. }
  153. return this;
  154. }
  155. })(jQuery);