jQuery plug-in to provide custom analytics. For those of us who can not use Google Analytics at work or just want to dork with something else.

jquery-analytics.js 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. // The MIT License (MIT)
  2. //
  3. // Copyright (c) 2013 Bryan Allred <bryan.allred@gmail.com>
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. // Check to see if a string starts with the given search criteria.
  23. // @param {String} search
  24. // @return {Boolean} a value indicating whether the string starts with the search criteria
  25. String.prototype.startsWith = function (search) {
  26. return this.indexOf(search) == 0;
  27. };
  28. // Check to see if a string ends with the given search criteria.
  29. // @param {String} search
  30. // @return {Boolean} a value indicating whether the string ends with the search criteria
  31. String.prototype.endsWith = function (search) {
  32. return this.lastIndexOf(search) == this.length - search.length;
  33. };
  34. (function ($) {
  35. // Declared outside of scope to maintain an accurate count.
  36. var uniqueId = 0;
  37. // Default settings which may be extended upon.
  38. var settings = {
  39. attributes: [],
  40. assignTo: ["a", "input[type='submit']"],
  41. captureOnce: false,
  42. client: null,
  43. id: "id",
  44. exclude: ".analytics-exclude",
  45. url: null
  46. };
  47. // Walk the tree of a given node.
  48. // @param {Object} element
  49. // @return {Array} path
  50. function walkTree(element) {
  51. var tree = [];
  52. var tagName = $(element).prop("tagName");
  53. if (tagName != undefined) {
  54. var parent = $(element).parent();
  55. if (parent != undefined) {
  56. $.each(walkTree($(element).parent()), function (i, node) {
  57. if ($(node).is(settings.exclude)) {
  58. tree = null;
  59. }
  60. else if (tree !== null) {
  61. tree.push(node);
  62. }
  63. });
  64. }
  65. if (tree !== null) {
  66. if (tagName == "HTML" || tagName == "BODY") {
  67. tree.push(tagName);
  68. }
  69. else {
  70. var tagId = $(element).analyticsUniqueId().attr("id");
  71. tree.push(tagName + '[id="' + tagId + '"]');
  72. }
  73. }
  74. }
  75. return tree;
  76. };
  77. // Identify the path to the node.
  78. // @param {Object} node
  79. function identifyPath(node) {
  80. // Assign identification to all relevant elements.
  81. walkTree(node);
  82. };
  83. // Initiate a trace on click.
  84. // @param {Object} e
  85. function initiateTrace(e) {
  86. // Locally scope this variable.
  87. $this = $(this);
  88. if (settings.url && !$this.is(".analytics-captured") && !$this.is(settings.exclude)) {
  89. // Walk the tree.
  90. var tree = walkTree($this);
  91. // Make sure the tree does not include an excluded section.
  92. if (tree !== null && tree.length > 0) {
  93. // Join all the nodes of the tree.
  94. tree = tree.join(' ');
  95. // We prevent the default action to allow the background call to succeed.
  96. var preventedHref = null;
  97. if ($this.attr("href")) {
  98. e.preventDefault();
  99. preventedHref = $this.attr("href");
  100. }
  101. // Initialize the data to be collected.
  102. var data = {};
  103. // Attach the object identifier.
  104. if (settings.id) {
  105. data[settings.id] = tree;
  106. }
  107. else {
  108. data["id"] = tree;
  109. }
  110. // Attach the client identifier if found.
  111. if (settings.client) {
  112. data["client"] = settings.client
  113. }
  114. // Assign any "data-analytics-" attributes.
  115. var dataAttributes = $this.data();
  116. for (var attribute in dataAttributes) {
  117. if (attribute.startsWith("analytics")) {
  118. var cleanName = attribute.replace(/analytics/g, '').toLowerCase();
  119. data[cleanName] = dataAttributes[attribute];
  120. }
  121. }
  122. // Assign the custom attributes requested to be collected.
  123. $.each($(settings.attributes), function (i, attribute) {
  124. data[attribute] = $this.attr(attribute);
  125. });
  126. // Send the analytics.
  127. $.ajax({
  128. type: "POST",
  129. url: settings.url,
  130. contentType: "application/x-www-form-urlencoded",
  131. data: data
  132. })
  133. .always(function () {
  134. if (settings.captureOnce) {
  135. $this.addClass("analytics-captured");
  136. }
  137. if (preventedHref) {
  138. window.location = preventedHref;
  139. }
  140. });
  141. }
  142. }
  143. };
  144. // Provide a unique identifier to an element if one has not already been assigned.
  145. // @return {Object} modified jQuery objects
  146. $.fn.analyticsUniqueId = function () {
  147. if (this.length == 0) {
  148. return;
  149. }
  150. return this.each(function () {
  151. if (!$(this).attr("id")) {
  152. $(this).attr("id", "analytics-id-" + ++uniqueId);
  153. }
  154. });
  155. };
  156. // Plug-in function providing easy access to analytics.
  157. // @param {Object} options
  158. // @returns {Object} modified jQuery objects
  159. $.fn.analytics = function (options) {
  160. if ($(this).length == 0) {
  161. return;
  162. }
  163. // Configure the default settings.
  164. settings = $.extend({}, settings, options);
  165. // Declare the selector to be used.
  166. var selector = settings.assignTo.join(",");
  167. return this.each(function () {
  168. // Itereate through all elements given on initiation.
  169. $(this).find(selector).andSelf().filter(selector)
  170. .each(function () {
  171. identifyPath($(this));
  172. $(this).on("click", initiateTrace);
  173. });
  174. })
  175. .on("DOMNodeInserted", function (e) {
  176. // This will capture any dynamically generated content.
  177. $(e.target).find(selector).andSelf().filter(selector)
  178. .each(function () {
  179. identifyPath($(this));
  180. $(this).on("click", initiateTrace);
  181. });
  182. });
  183. };
  184. })(jQuery);