xref: /plugin/autotooltip/script.js (revision 6bfd3f23b88eaf72b526530268de105d7e747a15)
1/**
2 * Javascript for the autotooltip plugin.
3 *
4 * @type {{show:function, hide:function}}
5 */
6var autotooltip = function($) {
7	var timer;
8	var TT_DELAY = 50;
9	var MAX_WIDTH = 500;
10	var moveCount = 0;
11	var isVisible;
12	var tt;
13
14
15	/**
16	 * Initialize the module.
17	 *
18	 * @private
19	 */
20	var _init = function() {
21		if (!tt) {
22			tt = $('<div class="plugin-autotooltip_tip"></div>');
23			$(document.body).append(tt);
24		}
25
26		$(document).on('mousemove', _move);
27		_init = function() {}; // Only once.
28	};
29
30
31	/**
32	 * Mousemove handler. When the mouse moves, so does the tooltip.
33	 *
34	 * @param {MouseEvent} e
35	 * @private
36	 */
37	var _move = function(e) {
38		if (isVisible) {
39			var localMoveCount = ++moveCount;
40			requestAnimationFrame(function() {
41				if (localMoveCount == moveCount) {
42					//TODO: Limit right/left pos too
43					var top = Math.max(e.pageY - tt.outerHeight() - 4, window.scrollY + 8);
44					tt.css({top: top + 'px', left: (e.pageX + 4) + 'px'});
45				}
46			});
47		}
48	};
49
50
51	/**
52	 * Show the tooltip with the given HTML.
53	 *
54	 * @param {String} html - The HTML content of the tooltip.
55	 * @param {String} classes - CSS classes to add.
56	 * @private
57	 */
58	var _show = function(html, classes) {
59		tt.html(html).css({width: 'auto'}).attr('class', 'plugin-autotooltip_tip ' + classes);
60		if (tt.width() > MAX_WIDTH) {
61			tt.css({width: MAX_WIDTH + 'px'});
62		}
63		isVisible = true;
64		clearInterval(timer);
65		timer = setTimeout(function() {
66			tt.addClass('plugin-autotooltip--visible');
67		}, TT_DELAY);
68	};
69
70
71	return {
72		/**
73		 * Show a tooltip.
74		 *
75		 * @param {Element} elt - Element containing all content.
76		 */
77		show: function(elt) {
78			_init();
79			_show($('.plugin-autotooltip-hidden-tip', elt).html(), $('.plugin-autotooltip-hidden-classes', elt).text());
80		},
81
82
83		/**
84		 * Hide the tooltip.
85		 */
86		hide: function() {
87			isVisible = false;
88			timer = setTimeout(function() {
89				tt.removeClass('plugin-autotooltip--visible');
90			}, TT_DELAY);
91		}
92	};
93}(jQuery);
94