UNPKG

2.84 kBJavaScriptView Raw
1(function ($) {
2 // Register namespace
3 $.extend(true, window, {
4 "Slick": {
5 "AutoTooltips": AutoTooltips
6 }
7 });
8
9 /**
10 * AutoTooltips plugin to show/hide tooltips when columns are too narrow to fit content.
11 * @constructor
12 * @param {boolean} [options.enableForCells=true] - Enable tooltip for grid cells
13 * @param {boolean} [options.enableForHeaderCells=false] - Enable tooltip for header cells
14 * @param {number} [options.maxToolTipLength=null] - The maximum length for a tooltip
15 */
16 function AutoTooltips(options) {
17 var _grid;
18 var _self = this;
19 var _defaults = {
20 enableForCells: true,
21 enableForHeaderCells: false,
22 maxToolTipLength: null,
23 replaceExisting: true
24 };
25
26 /**
27 * Initialize plugin.
28 */
29 function init(grid) {
30 options = $.extend(true, {}, _defaults, options);
31 _grid = grid;
32 if (options.enableForCells) _grid.onMouseEnter.subscribe(handleMouseEnter);
33 if (options.enableForHeaderCells) _grid.onHeaderMouseEnter.subscribe(handleHeaderMouseEnter);
34 }
35
36 /**
37 * Destroy plugin.
38 */
39 function destroy() {
40 if (options.enableForCells) _grid.onMouseEnter.unsubscribe(handleMouseEnter);
41 if (options.enableForHeaderCells) _grid.onHeaderMouseEnter.unsubscribe(handleHeaderMouseEnter);
42 }
43
44 /**
45 * Handle mouse entering grid cell to add/remove tooltip.
46 * @param {jQuery.Event} e - The event
47 */
48 function handleMouseEnter(e) {
49 var cell = _grid.getCellFromEvent(e);
50 if (cell) {
51 var $node = $(_grid.getCellNode(cell.row, cell.cell));
52 var text;
53 if (!$node.attr("title") || options.replaceExisting) {
54 if ($node.innerWidth() < $node[0].scrollWidth) {
55 text = $.trim($node.text());
56 if (options.maxToolTipLength && text.length > options.maxToolTipLength) {
57 text = text.substr(0, options.maxToolTipLength - 3) + "...";
58 }
59 } else {
60 text = "";
61 }
62 $node.attr("title", text);
63 }
64 $node = null;
65 }
66 }
67
68 /**
69 * Handle mouse entering header cell to add/remove tooltip.
70 * @param {jQuery.Event} e - The event
71 * @param {object} args.column - The column definition
72 */
73 function handleHeaderMouseEnter(e, args) {
74 var column = args.column,
75 $node = $(e.target).closest(".slick-header-column");
76 if (column && !column.toolTip) {
77 $node.attr("title", ($node.innerWidth() < $node[0].scrollWidth) ? column.name : "");
78 }
79 $node = null;
80 }
81
82 // Public API
83 $.extend(this, {
84 "init": init,
85 "destroy": destroy,
86 "pluginName": "AutoTooltips"
87 });
88 }
89})(jQuery);
\No newline at end of file