forked from Khan/khan-exercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jquery.qtip.js
3532 lines (2915 loc) · 103 KB
/
jquery.qtip.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* qTip2 - Pretty powerful tooltips - v2.0.1-31-
* http://qtip2.com
*
* Copyright (c) 2013 Craig Michael Thompson
* Released under the MIT, GPL licenses
* http://jquery.org/license
*
* Date: Tue Mar 5 2013 02:40 GMT+0000
* Plugins: svg ajax tips modal viewport imagemap ie6
* Styles: basic css3
*/
/*jslint browser: true, onevar: true, undef: true, nomen: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */
/*global window: false, jQuery: false, console: false, define: false */
/* Cache window, document, undefined */
(function( window, document, undefined ) {
// Uses AMD or browser globals to create a jQuery plugin.
(function( factory ) {
"use strict";
if(typeof define === 'function' && define.amd) {
define(['jquery'], factory);
}
else if(jQuery && !jQuery.fn.qtip) {
factory(jQuery);
}
}
(function($) {
/* This currently causes issues with Safari 6, so for it's disabled */
//"use strict"; // (Dis)able ECMAScript "strict" operation for this function. See more: http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
// Munge the primitives - Paul Irish tip
var TRUE = true,
FALSE = false,
NULL = null,
// Common variables
X = 'x', Y = 'y',
WIDTH = 'width',
HEIGHT = 'height',
// Positioning sides
TOP = 'top',
LEFT = 'left',
BOTTOM = 'bottom',
RIGHT = 'right',
CENTER = 'center',
// Position adjustment types
FLIP = 'flip',
FLIPINVERT = 'flipinvert',
SHIFT = 'shift',
// Used by image load detection (see core.js)
BLANKIMG = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==',
// Shortcut vars
QTIP, PLUGINS, MOUSE,
NAMESPACE = 'qtip',
HASATTR = 'data-hasqtip',
usedIDs = {},
widget = ['ui-widget', 'ui-tooltip'],
selector = 'div.qtip.'+NAMESPACE,
defaultClass = NAMESPACE + '-default',
focusClass = NAMESPACE + '-focus',
hoverClass = NAMESPACE + '-hover',
replaceSuffix = '_replacedByqTip',
oldtitle = 'oldtitle',
trackingBound;
// Store mouse coordinates
function storeMouse(event)
{
MOUSE = {
pageX: event.pageX,
pageY: event.pageY,
type: 'mousemove',
scrollX: window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft,
scrollY: window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
};
}
// Option object sanitizer
function sanitizeOptions(opts)
{
var invalid = function(a) { return a === NULL || 'object' !== typeof a; },
invalidContent = function(c) { return !$.isFunction(c) && ((!c && !c.attr) || c.length < 1 || ('object' === typeof c && !c.jquery && !c.then)); };
if(!opts || 'object' !== typeof opts) { return FALSE; }
if(invalid(opts.metadata)) {
opts.metadata = { type: opts.metadata };
}
if('content' in opts) {
if(invalid(opts.content) || opts.content.jquery) {
opts.content = { text: opts.content };
}
if(invalidContent(opts.content.text || FALSE)) {
opts.content.text = FALSE;
}
if('title' in opts.content) {
if(invalid(opts.content.title)) {
opts.content.title = { text: opts.content.title };
}
if(invalidContent(opts.content.title.text || FALSE)) {
opts.content.title.text = FALSE;
}
}
}
if('position' in opts && invalid(opts.position)) {
opts.position = { my: opts.position, at: opts.position };
}
if('show' in opts && invalid(opts.show)) {
opts.show = opts.show.jquery ? { target: opts.show } :
opts.show === TRUE ? { ready: TRUE } : { event: opts.show };
}
if('hide' in opts && invalid(opts.hide)) {
opts.hide = opts.hide.jquery ? { target: opts.hide } : { event: opts.hide };
}
if('style' in opts && invalid(opts.style)) {
opts.style = { classes: opts.style };
}
// Sanitize plugin options
$.each(PLUGINS, function() {
if(this.sanitize) { this.sanitize(opts); }
});
return opts;
}
/*
* Core plugin implementation
*/
function QTip(target, options, id, attr)
{
// Declare this reference
var self = this,
docBody = document.body,
tooltipID = NAMESPACE + '-' + id,
isPositioning = 0,
isDrawing = 0,
tooltip = $(),
namespace = '.qtip-' + id,
disabledClass = 'qtip-disabled',
elements, cache;
// Setup class attributes
self.id = id;
self.rendered = FALSE;
self.destroyed = FALSE;
self.elements = elements = { target: target };
self.timers = { img: {} };
self.options = options;
self.checks = {};
self.plugins = {};
self.cache = cache = {
event: {},
target: $(),
disabled: FALSE,
attr: attr,
onTarget: FALSE,
lastClass: ''
};
function convertNotation(notation)
{
var i = 0, obj, option = options,
// Split notation into array
levels = notation.split('.');
// Loop through
while( option = option[ levels[i++] ] ) {
if(i < levels.length) { obj = option; }
}
return [obj || options, levels.pop()];
}
function createWidgetClass(cls)
{
return widget.concat('').join(cls ? '-'+cls+' ' : ' ');
}
function setWidget()
{
var on = options.style.widget,
disabled = tooltip.hasClass(disabledClass);
tooltip.removeClass(disabledClass);
disabledClass = on ? 'ui-state-disabled' : 'qtip-disabled';
tooltip.toggleClass(disabledClass, disabled);
tooltip.toggleClass('ui-helper-reset '+createWidgetClass(), on).toggleClass(defaultClass, options.style.def && !on);
if(elements.content) {
elements.content.toggleClass( createWidgetClass('content'), on);
}
if(elements.titlebar) {
elements.titlebar.toggleClass( createWidgetClass('header'), on);
}
if(elements.button) {
elements.button.toggleClass(NAMESPACE+'-icon', !on);
}
}
function removeTitle(reposition)
{
if(elements.title) {
elements.titlebar.remove();
elements.titlebar = elements.title = elements.button = NULL;
// Reposition if enabled
if(reposition !== FALSE) { self.reposition(); }
}
}
function createButton()
{
var button = options.content.title.button,
isString = typeof button === 'string',
close = isString ? button : 'Close tooltip';
if(elements.button) { elements.button.remove(); }
// Use custom button if one was supplied by user, else use default
if(button.jquery) {
elements.button = button;
}
else {
elements.button = $('<a />', {
'class': 'qtip-close ' + (options.style.widget ? '' : NAMESPACE+'-icon'),
'title': close,
'aria-label': close
})
.prepend(
$('<span />', {
'class': 'ui-icon ui-icon-close',
'html': '×'
})
);
}
// Create button and setup attributes
elements.button.appendTo(elements.titlebar || tooltip)
.attr('role', 'button')
.click(function(event) {
if(!tooltip.hasClass(disabledClass)) { self.hide(event); }
return FALSE;
});
}
function createTitle()
{
var id = tooltipID+'-title';
// Destroy previous title element, if present
if(elements.titlebar) { removeTitle(); }
// Create title bar and title elements
elements.titlebar = $('<div />', {
'class': NAMESPACE + '-titlebar ' + (options.style.widget ? createWidgetClass('header') : '')
})
.append(
elements.title = $('<div />', {
'id': id,
'class': NAMESPACE + '-title',
'aria-atomic': TRUE
})
)
.insertBefore(elements.content)
// Button-specific events
.delegate('.qtip-close', 'mousedown keydown mouseup keyup mouseout', function(event) {
$(this).toggleClass('ui-state-active ui-state-focus', event.type.substr(-4) === 'down');
})
.delegate('.qtip-close', 'mouseover mouseout', function(event){
$(this).toggleClass('ui-state-hover', event.type === 'mouseover');
});
// Create button if enabled
if(options.content.title.button) { createButton(); }
}
function updateButton(button)
{
var elem = elements.button;
// Make sure tooltip is rendered and if not, return
if(!self.rendered) { return FALSE; }
if(!button) {
elem.remove();
}
else {
createButton();
}
}
function updateTitle(content, reposition)
{
var elem = elements.title;
// Make sure tooltip is rendered and if not, return
if(!self.rendered || !content) { return FALSE; }
// Use function to parse content
if($.isFunction(content)) {
content = content.call(target, cache.event, self);
}
// Remove title if callback returns false or null/undefined (but not '')
if(content === FALSE || (!content && content !== '')) { return removeTitle(FALSE); }
// Append new content if its a DOM array and show it if hidden
else if(content.jquery && content.length > 0) {
elem.empty().append(content.css({ display: 'block' }));
}
// Content is a regular string, insert the new content
else { elem.html(content); }
// Reposition if rnedered
if(reposition !== FALSE && self.rendered && tooltip[0].offsetWidth > 0) {
self.reposition(cache.event);
}
}
function deferredContent(deferred)
{
if(deferred && $.isFunction(deferred.done)) {
deferred.done(function(c) {
updateContent(c, null, FALSE);
});
}
}
function updateContent(content, reposition, checkDeferred)
{
var elem = elements.content;
// Make sure tooltip is rendered and content is defined. If not return
if(!self.rendered || !content) { return FALSE; }
// Use function to parse content
if($.isFunction(content)) {
content = content.call(target, cache.event, self) || '';
}
// Handle deferred content
if(checkDeferred !== FALSE) {
deferredContent(options.content.deferred);
}
// Append new content if its a DOM array and show it if hidden
if(content.jquery && content.length > 0) {
elem.empty().append(content.css({ display: 'block' }));
}
// Content is a regular string, insert the new content
else { elem.html(content); }
/*
* New images loaded detection method slimmed down from David DeSandro's plugin
* GitHub: https://github.com/desandro/imagesloaded/
*/
function imagesLoaded(next) {
var elem = $(this),
images = elem.find('img').add( elem.filter('img') ),
loaded = [];
function imgLoaded( img ) {
// don't proceed if BLANKIMG image, or image is already loaded
if(img.src === BLANKIMG || $.inArray(img, loaded) !== -1) { return; }
// store element in loaded images array
loaded.push(img);
// cache image and its state for future calls
$.data(img, 'imagesLoaded', { src: img.src });
// call doneLoading and clean listeners if all images are loaded
if(images.length === loaded.length) {
setTimeout(next);
images.unbind('.imagesLoaded');
}
}
// No images? Proceed with next
if(!images.length) { return next(); }
images.bind('load.imagesLoaded error.imagesLoaded', function(event) {
imgLoaded(event.target);
})
.each(function(i, el) {
var src = el.src, cached = $.data(el, 'imagesLoaded');
/*
* Find out if this image has been already checked for status, and
* if it was and src has not changed, call imgLoaded on it. Also,
* if complete is true and browser supports natural sizes, try to
* check for image status manually
*/
if((cached && cached.src === src) || (el.complete && el.naturalWidth)) {
imgLoaded(el);
}
/*
* Cached images don't fire load sometimes, so we reset src, but only when
* dealing with IE, or image is complete (loaded) and failed manual check
*
* Webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
*/
else if(el.readyState || el.complete) {
el.src = BLANKIMG; el.src = src;
}
});
}
/*
* If we're still rendering... insert into 'fx' queue our image dimension
* checker which will halt the showing of the tooltip until image dimensions
* can be detected properly.
*/
if(self.rendered < 0) { tooltip.queue('fx', imagesLoaded); }
// We're fully rendered, so reset isDrawing flag and proceed without queue delay
else { isDrawing = 0; imagesLoaded.call(tooltip[0], $.noop); }
return self;
}
function assignEvents()
{
var posOptions = options.position,
targets = {
show: options.show.target,
hide: options.hide.target,
viewport: $(posOptions.viewport),
document: $(document),
body: $(document.body),
window: $(window)
},
events = {
show: $.trim('' + options.show.event).split(' '),
hide: $.trim('' + options.hide.event).split(' ')
},
IE6 = PLUGINS.ie === 6;
// Define show event method
function showMethod(event)
{
if(tooltip.hasClass(disabledClass)) { return FALSE; }
// Clear hide timers
clearTimeout(self.timers.show);
clearTimeout(self.timers.hide);
// Start show timer
var callback = function(){ self.toggle(TRUE, event); };
if(options.show.delay > 0) {
self.timers.show = setTimeout(callback, options.show.delay);
}
else{ callback(); }
}
// Define hide method
function hideMethod(event)
{
if(tooltip.hasClass(disabledClass) || isPositioning || isDrawing) { return FALSE; }
// Check if new target was actually the tooltip element
var relatedTarget = $(event.relatedTarget),
ontoTooltip = relatedTarget.closest(selector)[0] === tooltip[0],
ontoTarget = relatedTarget[0] === targets.show[0];
// Clear timers and stop animation queue
clearTimeout(self.timers.show);
clearTimeout(self.timers.hide);
// Prevent hiding if tooltip is fixed and event target is the tooltip. Or if mouse positioning is enabled and cursor momentarily overlaps
if(this !== relatedTarget[0] &&
(posOptions.target === 'mouse' && ontoTooltip) ||
(options.hide.fixed && (
(/mouse(out|leave|move)/).test(event.type) && (ontoTooltip || ontoTarget))
)) {
try { event.preventDefault(); event.stopImmediatePropagation(); } catch(e) {} return;
}
// If tooltip has displayed, start hide timer
if(options.hide.delay > 0) {
self.timers.hide = setTimeout(function(){ self.hide(event); }, options.hide.delay);
}
else{ self.hide(event); }
}
// Define inactive method
function inactiveMethod(event)
{
if(tooltip.hasClass(disabledClass)) { return FALSE; }
// Clear timer
clearTimeout(self.timers.inactive);
self.timers.inactive = setTimeout(function(){ self.hide(event); }, options.hide.inactive);
}
function repositionMethod(event) {
if(self.rendered && tooltip[0].offsetWidth > 0) { self.reposition(event); }
}
// On mouseenter/mouseleave...
tooltip.bind('mouseenter'+namespace+' mouseleave'+namespace, function(event) {
var state = event.type === 'mouseenter';
// Focus the tooltip on mouseenter (z-index stacking)
if(state) { self.focus(event); }
// Add hover class
tooltip.toggleClass(hoverClass, state);
});
// If using mouseout/mouseleave as a hide event...
if(/mouse(out|leave)/i.test(options.hide.event)) {
// Hide tooltips when leaving current window/frame (but not select/option elements)
if(options.hide.leave === 'window') {
targets.document.bind('mouseout'+namespace+' blur'+namespace, function(event) {
if(!/select|option/.test(event.target.nodeName) && !event.relatedTarget) {
self.hide(event);
}
});
}
}
// Enable hide.fixed
if(options.hide.fixed) {
// Add tooltip as a hide target
targets.hide = targets.hide.add(tooltip);
// Clear hide timer on tooltip hover to prevent it from closing
tooltip.bind('mouseover'+namespace, function() {
if(!tooltip.hasClass(disabledClass)) { clearTimeout(self.timers.hide); }
});
}
/*
* Make sure hoverIntent functions properly by using mouseleave to clear show timer if
* mouseenter/mouseout is used for show.event, even if it isn't in the users options.
*/
else if(/mouse(over|enter)/i.test(options.show.event)) {
targets.hide.bind('mouseleave'+namespace, function(event) {
clearTimeout(self.timers.show);
});
}
// Hide tooltip on document mousedown if unfocus events are enabled
if(('' + options.hide.event).indexOf('unfocus') > -1) {
posOptions.container.closest('html').bind('mousedown'+namespace+' touchstart'+namespace, function(event) {
var elem = $(event.target),
enabled = self.rendered && !tooltip.hasClass(disabledClass) && tooltip[0].offsetWidth > 0,
isAncestor = elem.parents(selector).filter(tooltip[0]).length > 0;
if(elem[0] !== target[0] && elem[0] !== tooltip[0] && !isAncestor &&
!target.has(elem[0]).length && enabled
) {
self.hide(event);
}
});
}
// Check if the tooltip hides when inactive
if('number' === typeof options.hide.inactive) {
// Bind inactive method to target as a custom event
targets.show.bind('qtip-'+id+'-inactive', inactiveMethod);
// Define events which reset the 'inactive' event handler
$.each(QTIP.inactiveEvents, function(index, type){
targets.hide.add(elements.tooltip).bind(type+namespace+'-inactive', inactiveMethod);
});
}
// Apply hide events
$.each(events.hide, function(index, type) {
var showIndex = $.inArray(type, events.show),
targetHide = $(targets.hide);
// Both events and targets are identical, apply events using a toggle
if((showIndex > -1 && targetHide.add(targets.show).length === targetHide.length) || type === 'unfocus')
{
targets.show.bind(type+namespace, function(event) {
if(tooltip[0].offsetWidth > 0) { hideMethod(event); }
else { showMethod(event); }
});
// Don't bind the event again
delete events.show[ showIndex ];
}
// Events are not identical, bind normally
else { targets.hide.bind(type+namespace, hideMethod); }
});
// Apply show events
$.each(events.show, function(index, type) {
targets.show.bind(type+namespace, showMethod);
});
// Check if the tooltip hides when mouse is moved a certain distance
if('number' === typeof options.hide.distance) {
// Bind mousemove to target to detect distance difference
targets.show.add(tooltip).bind('mousemove'+namespace, function(event) {
var origin = cache.origin || {},
limit = options.hide.distance,
abs = Math.abs;
// Check if the movement has gone beyond the limit, and hide it if so
if(abs(event.pageX - origin.pageX) >= limit || abs(event.pageY - origin.pageY) >= limit) {
self.hide(event);
}
});
}
// Mouse positioning events
if(posOptions.target === 'mouse') {
// Cache mousemove coords on show targets
targets.show.bind('mousemove'+namespace, storeMouse);
// If mouse adjustment is on...
if(posOptions.adjust.mouse) {
// Apply a mouseleave event so we don't get problems with overlapping
if(options.hide.event) {
// Hide when we leave the tooltip and not onto the show target
tooltip.bind('mouseleave'+namespace, function(event) {
if((event.relatedTarget || event.target) !== targets.show[0]) { self.hide(event); }
});
// Track if we're on the target or not
elements.target.bind('mouseenter'+namespace+' mouseleave'+namespace, function(event) {
cache.onTarget = event.type === 'mouseenter';
});
}
// Update tooltip position on mousemove
targets.document.bind('mousemove'+namespace, function(event) {
// Update the tooltip position only if the tooltip is visible and adjustment is enabled
if(self.rendered && cache.onTarget && !tooltip.hasClass(disabledClass) && tooltip[0].offsetWidth > 0) {
self.reposition(event || MOUSE);
}
});
}
}
// Adjust positions of the tooltip on window resize if enabled
if(posOptions.adjust.resize || targets.viewport.length) {
($.event.special.resize ? targets.viewport : targets.window).bind('resize'+namespace, repositionMethod);
}
// Adjust tooltip position on scroll of the window or viewport element if present
if(posOptions.adjust.scroll) {
targets.window.add(posOptions.container).bind('scroll'+namespace, repositionMethod);
}
}
function unassignEvents()
{
var targets = [
options.show.target[0],
options.hide.target[0],
self.rendered && elements.tooltip[0],
options.position.container[0],
options.position.viewport[0],
options.position.container.closest('html')[0], // unfocus
window,
document
];
// Check if tooltip is rendered
if(self.rendered) {
$([]).pushStack( $.grep(targets, function(i){ return typeof i === 'object'; }) ).unbind(namespace);
}
// Tooltip isn't yet rendered, remove render event
else { options.show.target.unbind(namespace+'-create'); }
}
// Setup builtin .set() option checks
self.checks.builtin = {
// Core checks
'^id$': function(obj, o, v) {
var id = v === TRUE ? QTIP.nextid : v,
tooltipID = NAMESPACE + '-' + id;
if(id !== FALSE && id.length > 0 && !$('#'+tooltipID).length) {
tooltip[0].id = tooltipID;
elements.content[0].id = tooltipID + '-content';
elements.title[0].id = tooltipID + '-title';
}
},
// Content checks
'^content.text$': function(obj, o, v) { updateContent(options.content.text); },
'^content.deferred$': function(obj, o, v) { deferredContent(options.content.deferred); },
'^content.title.text$': function(obj, o, v) {
// Remove title if content is null
if(!v) { return removeTitle(); }
// If title isn't already created, create it now and update
if(!elements.title && v) { createTitle(); }
updateTitle(v);
},
'^content.title.button$': function(obj, o, v){ updateButton(v); },
// Position checks
'^position.(my|at)$': function(obj, o, v){
// Parse new corner value into Corner objecct
if('string' === typeof v) {
obj[o] = new PLUGINS.Corner(v);
}
},
'^position.container$': function(obj, o, v){
if(self.rendered) { tooltip.appendTo(v); }
},
// Show checks
'^show.ready$': function() {
if(!self.rendered) { self.render(1); }
else { self.toggle(TRUE); }
},
// Style checks
'^style.classes$': function(obj, o, v) {
tooltip.attr('class', NAMESPACE + ' qtip ' + v);
},
'^style.width|height': function(obj, o, v) {
tooltip.css(o, v);
},
'^style.widget|content.title': setWidget,
// Events check
'^events.(render|show|move|hide|focus|blur)$': function(obj, o, v) {
tooltip[($.isFunction(v) ? '' : 'un') + 'bind']('tooltip'+o, v);
},
// Properties which require event reassignment
'^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)': function() {
var posOptions = options.position;
// Set tracking flag
tooltip.attr('tracking', posOptions.target === 'mouse' && posOptions.adjust.mouse);
// Reassign events
unassignEvents(); assignEvents();
}
};
$.extend(self, {
/*
* Psuedo-private API methods
*/
_triggerEvent: function(type, args, event)
{
var callback = $.Event('tooltip'+type);
callback.originalEvent = (event ? $.extend({}, event) : NULL) || cache.event || NULL;
tooltip.trigger(callback, [self].concat(args || []));
return !callback.isDefaultPrevented();
},
/*
* Public API methods
*/
render: function(show)
{
if(self.rendered) { return self; } // If tooltip has already been rendered, exit
var text = options.content.text,
title = options.content.title,
posOptions = options.position;
// Add ARIA attributes to target
$.attr(target[0], 'aria-describedby', tooltipID);
// Create tooltip element
tooltip = elements.tooltip = $('<div/>', {
'id': tooltipID,
'class': [ NAMESPACE, defaultClass, options.style.classes, NAMESPACE + '-pos-' + options.position.my.abbrev() ].join(' '),
'width': options.style.width || '',
'height': options.style.height || '',
'tracking': posOptions.target === 'mouse' && posOptions.adjust.mouse,
/* ARIA specific attributes */
'role': 'alert',
'aria-live': 'polite',
'aria-atomic': FALSE,
'aria-describedby': tooltipID + '-content',
'aria-hidden': TRUE
})
.toggleClass(disabledClass, cache.disabled)
.data('qtip', self)
.appendTo(options.position.container)
.append(
// Create content element
elements.content = $('<div />', {
'class': NAMESPACE + '-content',
'id': tooltipID + '-content',
'aria-atomic': TRUE
})
);
// Set rendered flag and prevent redundant reposition calls for now
self.rendered = -1;
isPositioning = 1;
// Create title...
if(title.text) {
createTitle();
// Update title only if its not a callback (called in toggle if so)
if(!$.isFunction(title.text)) { updateTitle(title.text, FALSE); }
}
// Create button
else if(title.button) { createButton(); }
// Set proper rendered flag and update content if not a callback function (called in toggle)
if(!$.isFunction(text) || text.then) { updateContent(text, FALSE); }
self.rendered = TRUE;
// Setup widget classes
setWidget();
// Assign passed event callbacks (before plugins!)
$.each(options.events, function(name, callback) {
if($.isFunction(callback)) {
tooltip.bind(name === 'toggle' ? 'tooltipshow tooltiphide' : 'tooltip'+name, callback);
}
});
// Initialize 'render' plugins
$.each(PLUGINS, function() {
if(this.initialize === 'render') { this(self); }
});
// Assign events
assignEvents();
/* Queue this part of the render process in our fx queue so we can
* load images before the tooltip renders fully.
*
* See: updateContent method
*/
tooltip.queue('fx', function(next) {
// tooltiprender event
self._triggerEvent('render');
// Reset flags
isPositioning = 0;
// Show tooltip if needed
if(options.show.ready || show) {
self.toggle(TRUE, cache.event, FALSE);
}
next(); // Move on to next method in queue
});
return self;
},
get: function(notation)
{
var result, o;
switch(notation.toLowerCase())
{
case 'dimensions':
result = {
height: tooltip.outerHeight(FALSE),
width: tooltip.outerWidth(FALSE)
};
break;
case 'offset':
result = PLUGINS.offset(tooltip, options.position.container);
break;
default:
o = convertNotation(notation.toLowerCase());
result = o[0][ o[1] ];
result = result.precedance ? result.string() : result;
break;
}
return result;
},
set: function(option, value)
{
var rmove = /^position\.(my|at|adjust|target|container)|style|content|show\.ready/i,
rdraw = /^content\.(title|attr)|style/i,
reposition = FALSE,
checks = self.checks,
name;
function callback(notation, args) {
var category, rule, match;
for(category in checks) {
for(rule in checks[category]) {
if(match = (new RegExp(rule, 'i')).exec(notation)) {
args.push(match);
checks[category][rule].apply(self, args);
}
}
}
}
// Convert singular option/value pair into object form
if('string' === typeof option) {
name = option; option = {}; option[name] = value;
}
else { option = $.extend(TRUE, {}, option); }
// Set all of the defined options to their new values
$.each(option, function(notation, value) {
var obj = convertNotation( notation.toLowerCase() ), previous;
// Set new obj value
previous = obj[0][ obj[1] ];
obj[0][ obj[1] ] = 'object' === typeof value && value.nodeType ? $(value) : value;
// Set the new params for the callback
option[notation] = [obj[0], obj[1], value, previous];
// Also check if we need to reposition
reposition = rmove.test(notation) || reposition;
});
// Re-sanitize options
sanitizeOptions(options);
/*
* Execute any valid callbacks for the set options
* Also set isPositioning/isDrawing so we don't get loads of redundant repositioning calls.
*/
isPositioning = 1; $.each(option, callback); isPositioning = 0;
// Update position if needed
if(self.rendered && tooltip[0].offsetWidth > 0 && reposition) {
self.reposition( options.position.target === 'mouse' ? NULL : cache.event );
}
return self;
},
toggle: function(state, event)
{
// Try to prevent flickering when tooltip overlaps show element
if(event) {
if((/over|enter/).test(event.type) && (/out|leave/).test(cache.event.type) &&
options.show.target.add(event.target).length === options.show.target.length &&
tooltip.has(event.relatedTarget).length) {
return self;
}
// Cache event
cache.event = $.extend({}, event);
}
// Render the tooltip if showing and it isn't already
if(!self.rendered) { return state ? self.render(1) : self; }
var type = state ? 'show' : 'hide',
opts = options[type],
otherOpts = options[ !state ? 'show' : 'hide' ],
posOptions = options.position,
contentOptions = options.content,
width = tooltip.css('width'),
visible = tooltip[0].offsetWidth > 0,
animate = state || opts.target.length === 1,
sameTarget = !event || opts.target.length < 2 || cache.target[0] === event.target,
showEvent, delay;
// Detect state if valid one isn't provided
if((typeof state).search('boolean|number')) { state = !visible; }
// Return if element is already in correct state
if(!tooltip.is(':animated') && visible === state && sameTarget) { return self; }
// tooltipshow/tooltiphide events
if(!self._triggerEvent(type, [90])) { return self; }