PageRenderTime 26ms CodeModel.GetById 10ms RepoModel.GetById 1ms app.codeStats 0ms

/src/javascripts/jquery.tipsy.js

https://github.com/bigmlcom/tipsy
JavaScript | 357 lines | 271 code | 49 blank | 37 comment | 83 complexity | 4a4aa6afd4f02c9fbd445ab7f9086244 MD5 | raw file
Possible License(s): MIT
  1. // tipsy, facebook style tooltips for jquery
  2. // version 1.0.0a
  3. // (c) 2008-2010 jason frame [jason@onehackoranother.com]
  4. // released under the MIT license
  5. // Modified by Justin Donaldson [donaldson@bigml.com]
  6. // Added:
  7. // 1) Correctly handle svg elements (title children and/or xlink:title attr)
  8. // 2) Add some new dynamic gravity placement functions autoNWNE and autoSWSE
  9. // 3) z-index override for tipsies on top of tipsies
  10. // 4) Custom className argument that allows adding classes to the tipsy popup
  11. // 5) Add custom cancelHide function argument that can override a tipsy hide
  12. // behavior. This is useful when you wish to keep a parent tipsy open while
  13. // its child is still active.
  14. (function($) {
  15. function maybeCall(thing, ctx) {
  16. return (typeof thing == 'function') ? (thing.call(ctx)) : thing;
  17. }
  18. // CAUTION the current implementation does not allow for tipsied elements to stay out of DOM (in between events)
  19. // i.e. don't remove, store, then re-insert tipsied elements (and why would you want to do that anyway?)
  20. var garbageCollect = (function() {
  21. var currentInterval;
  22. var to = null;
  23. var tipsies = [];
  24. function _do() {
  25. for (var i = 0; i < tipsies.length;) {
  26. var t = tipsies[i];
  27. // FIXME? the 2nd (non-paranoid) check is from the link below, it should be replaced if a better way is found
  28. // http://stackoverflow.com/questions/4040715/check-if-cached-jquery-object-is-still-in-dom
  29. if (t.options.gcInterval === 0 || t.$element.closest('body').length === 0) {
  30. t.hoverState = 'out';
  31. t.hide();
  32. tipsies.splice(i,1);
  33. } else {
  34. i++;
  35. }
  36. }
  37. }
  38. function _loop() {
  39. to = setTimeout(function() { _do(); _loop(); }, currentInterval);
  40. }
  41. return function(t) {
  42. if (t.options.gcInterval === 0) return;
  43. if (to && t.options.gcInterval < currentInterval) {
  44. clearTimeout(to); to = null;
  45. currentInterval = t.options.gcInterval;
  46. }
  47. tipsies.push(t);
  48. if (!to) _loop();
  49. };
  50. })();
  51. function Tipsy(element, options) {
  52. this.$element = $(element);
  53. this.options = options;
  54. this.enabled = true;
  55. this.fixTitle();
  56. garbageCollect(this);
  57. }
  58. Tipsy.prototype = {
  59. show: function() {
  60. var title = this.getTitle();
  61. if (title && this.enabled) {
  62. var $tip = this.tip();
  63. $tip.find('.tipsy-inner')[this.options.html ? 'html' : 'text'](title);
  64. $tip[0].className = 'tipsy'; // reset classname in case of dynamic gravity
  65. $tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).prependTo(document.body);
  66. var pos = $.extend({}, this.$element.offset(), {
  67. width: this.$element[0].offsetWidth || 0,
  68. height: this.$element[0].offsetHeight || 0
  69. });
  70. if (typeof this.$element[0].nearestViewportElement == 'object') {
  71. // SVG
  72. var el = this.$element[0];
  73. var rect = el.getBoundingClientRect();
  74. pos.width = rect.width;
  75. pos.height = rect.height;
  76. }
  77. var actualWidth = $tip[0].offsetWidth,
  78. actualHeight = $tip[0].offsetHeight,
  79. gravity = maybeCall(this.options.gravity, this.$element[0]);
  80. var tp;
  81. switch (gravity.charAt(0)) {
  82. case 'n':
  83. tp = {top: pos.top + pos.height + this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
  84. break;
  85. case 's':
  86. tp = {top: pos.top - actualHeight - this.options.offset, left: pos.left + pos.width / 2 - actualWidth / 2};
  87. break;
  88. case 'e':
  89. tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth - this.options.offset};
  90. break;
  91. case 'w':
  92. tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width + this.options.offset};
  93. break;
  94. }
  95. if (gravity.length == 2) {
  96. if (gravity.charAt(1) == 'w') {
  97. tp.left = pos.left + pos.width / 2 - 15;
  98. } else {
  99. tp.left = pos.left + pos.width / 2 - actualWidth + 15;
  100. }
  101. }
  102. $tip.css(tp).addClass('tipsy-' + gravity);
  103. $tip.find('.tipsy-arrow')[0].className = 'tipsy-arrow tipsy-arrow-' + gravity.charAt(0);
  104. if (this.options.className) {
  105. $tip.addClass(maybeCall(this.options.className, this.$element[0]));
  106. }
  107. if (this.options.fade) {
  108. $tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: this.options.opacity});
  109. } else {
  110. $tip.css({visibility: 'visible', opacity: this.options.opacity});
  111. }
  112. $tip.css({'z-index':this.options.zIndex});
  113. var t = this;
  114. var set_hovered = function(set_hover){
  115. return function(){
  116. t.$tip.stop();
  117. t.tipHovered = set_hover;
  118. if (!set_hover){
  119. if (t.options.delayOut === 0 && t.options.trigger != 'manual') {
  120. t.hide();
  121. } else {
  122. setTimeout(function() {
  123. if (t.hoverState == 'out') t.hide(); }, t.options.delayOut);
  124. }
  125. }
  126. };
  127. };
  128. $tip.hover(set_hovered(true), set_hovered(false));
  129. }
  130. },
  131. hide: function() {
  132. if (this.options.fade) {
  133. this.tip().stop().fadeOut(function() { $(this).remove(); });
  134. } else {
  135. if (this.options.cancelHide == null || !this.options.cancelHide()){
  136. this.tip().remove();
  137. }
  138. }
  139. },
  140. fixTitle: function() {
  141. var $e = this.$element;
  142. if ($e.attr('title') || typeof($e.attr('original-title')) != 'string') {
  143. $e.attr('original-title', $e.attr('title') || '').removeAttr('title');
  144. }
  145. if (typeof $e.context.nearestViewportElement == 'object'){
  146. if ($e.children('title').length){
  147. $e.append('<original-title>' + ($e.children('title').text() || '') + '</original-title>')
  148. .children('title').remove();
  149. }
  150. }
  151. },
  152. getTitle: function() {
  153. var title, $e = this.$element, o = this.options;
  154. this.fixTitle();
  155. if (typeof o.title == 'string') {
  156. var title_name = o.title == 'title' ? 'original-title' : o.title;
  157. if ($e.children(title_name).length){
  158. title = $e.children(title_name).html();
  159. } else{
  160. title = $e.attr(title_name);
  161. if (typeof title == 'undefined') title = ''
  162. }
  163. } else if (typeof o.title == 'function') {
  164. title = o.title.call($e[0]);
  165. }
  166. title = ('' + title).replace(/(^\s*|\s*$)/, "");
  167. return title || o.fallback;
  168. },
  169. tip: function() {
  170. if (!this.$tip) {
  171. this.$tip = $('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>');
  172. }
  173. return this.$tip;
  174. },
  175. validate: function() {
  176. if (!this.$element[0].parentNode) {
  177. this.hide();
  178. this.$element = null;
  179. this.options = null;
  180. }
  181. },
  182. enable: function() { this.enabled = true; },
  183. disable: function() { this.enabled = false; },
  184. toggleEnabled: function() { this.enabled = !this.enabled; }
  185. };
  186. $.fn.tipsy = function(options) {
  187. if (options === true) {
  188. return this.data('tipsy');
  189. } else if (typeof options == 'string') {
  190. $(this).each(function(i,el){
  191. if ($(el).data('tipsy')) {
  192. tipsy = $(el).data('tipsy')
  193. tipsy[options]();
  194. }
  195. });
  196. return this;
  197. }
  198. options = $.extend({}, $.fn.tipsy.defaults, options);
  199. if (options.hoverlock && options.delayOut === 0) {
  200. options.delayOut = 100;
  201. }
  202. function get(ele) {
  203. var tipsy = $.data(ele, 'tipsy');
  204. if (!tipsy) {
  205. tipsy = new Tipsy(ele, $.fn.tipsy.elementOptions(ele, options));
  206. $.data(ele, 'tipsy', tipsy);
  207. }
  208. return tipsy;
  209. }
  210. function enter() {
  211. var tipsy = get(this);
  212. tipsy.hoverState = 'in';
  213. if (options.delayIn === 0) {
  214. tipsy.show();
  215. } else {
  216. tipsy.fixTitle();
  217. setTimeout(function() { if (tipsy.hoverState == 'in') tipsy.show(); }, options.delayIn);
  218. }
  219. }
  220. function leave() {
  221. var tipsy = get(this);
  222. tipsy.hoverState = 'out';
  223. if (options.delayOut === 0) {
  224. tipsy.hide();
  225. } else {
  226. var to = function() {
  227. if (!tipsy.tipHovered || !options.hoverlock){
  228. if (tipsy.hoverState == 'out') tipsy.hide();
  229. }
  230. };
  231. setTimeout(to, options.delayOut);
  232. }
  233. }
  234. if (!options.live) this.each(function() { get(this); });
  235. if (options.trigger != 'manual') {
  236. var binder = options.live ? 'live' : 'bind',
  237. eventIn = options.trigger == 'hover' ? 'mouseenter' : 'focus',
  238. eventOut = options.trigger == 'hover' ? 'mouseleave' : 'blur';
  239. this[binder](eventIn, enter)[binder](eventOut, leave);
  240. }
  241. return this;
  242. };
  243. $.fn.tipsy.defaults = {
  244. className: null,
  245. delayIn: 0,
  246. delayOut: 0,
  247. fade: false,
  248. 'zIndex': 100000,
  249. fallback: '',
  250. cancelHide: null,
  251. gcInterval: 0,
  252. gravity: 'n',
  253. html: false,
  254. live: false,
  255. offset: 0,
  256. opacity: 0.8,
  257. title: 'title',
  258. trigger: 'hover',
  259. hoverlock: false
  260. };
  261. // Overwrite this method to provide options on a per-element basis.
  262. // For example, you could store the gravity in a 'tipsy-gravity' attribute:
  263. // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
  264. // (remember - do not modify 'options' in place!)
  265. $.fn.tipsy.elementOptions = function(ele, options) {
  266. return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
  267. };
  268. $.fn.tipsy.autoNS = function() {
  269. return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
  270. };
  271. $.fn.tipsy.autoWE = function() {
  272. return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
  273. };
  274. $.fn.tipsy.autoNWNE = function() {
  275. return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'ne' : 'nw';
  276. };
  277. $.fn.tipsy.autoSWSE = function() {
  278. return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'se' : 'sw';
  279. };
  280. /**
  281. * yields a closure of the supplied parameters, producing a function that takes
  282. * no arguments and is suitable for use as an autogravity function like so:
  283. *
  284. * @param margin (int) - distance from the viewable region edge that an
  285. * element should be before setting its tooltip's gravity to be away
  286. * from that edge.
  287. * @param prefer (string, e.g. 'n', 'sw', 'w') - the direction to prefer
  288. * if there are no viewable region edges effecting the tooltip's
  289. * gravity. It will try to vary from this minimally, for example,
  290. * if 'sw' is preferred and an element is near the right viewable
  291. * region edge, but not the top edge, it will set the gravity for
  292. * that element's tooltip to be 'se', preserving the southern
  293. * component.
  294. */
  295. $.fn.tipsy.autoBounds = function(margin, prefer) {
  296. return function() {
  297. var dir = {ns: prefer[0], ew: (prefer.length > 1 ? prefer[1] : false)},
  298. boundTop = $(document).scrollTop() + margin,
  299. boundLeft = $(document).scrollLeft() + margin,
  300. $this = $(this);
  301. if ($this.offset().top < boundTop) dir.ns = 'n';
  302. if ($this.offset().left < boundLeft) dir.ew = 'w';
  303. if ($(window).width() + $(document).scrollLeft() - $this.offset().left < margin) dir.ew = 'e';
  304. if ($(window).height() + $(document).scrollTop() - $this.offset().top < margin) dir.ns = 's';
  305. return dir.ns + (dir.ew ? dir.ew : '');
  306. };
  307. };
  308. })(jQuery);