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 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. tree.push(node);
  58. });
  59. }
  60. if (tagName == "HTML" || tagName == "BODY") {
  61. tree.push(tagName);
  62. }
  63. else {
  64. var tagId = $(element).analyticsUniqueId().attr("id");
  65. tree.push(tagName + '[id="' + tagId + '"]');
  66. }
  67. }
  68. return tree;
  69. };
  70. // Identify the path to the node.
  71. // @param {Object} node
  72. function identifyPath(node) {
  73. // Assign identification to all relevant elements.
  74. walkTree(node);
  75. };
  76. // Initiate a trace on click.
  77. // @param {Object} e
  78. function initiateTrace(e) {
  79. // Locally scope this variable.
  80. $this = $(this);
  81. if (settings.url && !$this.is(".analytics-captured") && !$this.is(settings.exclude)) {
  82. // We prevent the default action to allow the background call to succeed.
  83. var preventedHref = null;
  84. if ($this.attr("href")) {
  85. e.preventDefault();
  86. preventedHref = $this.attr("href");
  87. }
  88. // Initialize the data to be collected.
  89. var data = {};
  90. // Attach the object identifier.
  91. var tree = walkTree($this).join(' ');
  92. if (settings.id) {
  93. data[settings.id] = tree;
  94. }
  95. else {
  96. data["id"] = tree;
  97. }
  98. // Attach the client identifier if found.
  99. if (settings.client) {
  100. data["client"] = settings.client
  101. }
  102. // Assign any "data-analytics-" attributes.
  103. var dataAttributes = $this.data();
  104. for (var attribute in dataAttributes) {
  105. if (attribute.startsWith("analytics")) {
  106. var cleanName = attribute.replace(/analytics/g, '').toLowerCase();
  107. data[cleanName] = dataAttributes[attribute];
  108. }
  109. }
  110. // Assign the custom attributes requested to be collected.
  111. $.each($(settings.attributes), function (i, attribute) {
  112. data[attribute] = $this.attr(attribute);
  113. });
  114. // Send the analytics.
  115. $.ajax({
  116. type: "POST",
  117. url: settings.url,
  118. contentType: "application/x-www-form-urlencoded",
  119. data: data
  120. })
  121. .always(function () {
  122. if (settings.captureOnce) {
  123. $this.addClass("analytics-captured");
  124. }
  125. if (preventedHref) {
  126. window.location = preventedHref;
  127. }
  128. });
  129. }
  130. };
  131. // Provide a unique identifier to an element if one has not already been assigned.
  132. // @return {Object} modified jQuery objects
  133. $.fn.analyticsUniqueId = function () {
  134. if (this.length == 0) {
  135. return;
  136. }
  137. return this.each(function () {
  138. if (!$(this).attr("id")) {
  139. $(this).attr("id", "analytics-id-" + ++uniqueId);
  140. }
  141. });
  142. };
  143. // Plug-in function providing easy access to analytics.
  144. // @param {Object} options
  145. // @returns {Object} modified jQuery objects
  146. $.fn.analytics = function (options) {
  147. if ($(this).length == 0) {
  148. return;
  149. }
  150. // Configure the default settings.
  151. settings = $.extend({}, settings, options);
  152. // Declare the selector to be used.
  153. var selector = settings.assignTo.join(",");
  154. return this.each(function () {
  155. // Itereate through all elements given on initiation.
  156. $(this).find(selector).andSelf().filter(selector)
  157. .each(function () {
  158. identifyPath($(this));
  159. $(this).on("click", initiateTrace);
  160. });
  161. })
  162. .on("DOMNodeInserted", function (e) {
  163. // This will capture any dynamically generated content.
  164. $(e.target).find(selector).andSelf().filter(selector)
  165. .each(function () {
  166. identifyPath($(this));
  167. $(this).on("click", initiateTrace);
  168. });
  169. });
  170. };
  171. })(jQuery);