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.2KB

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