source: branches/2.4/themes/default/js/plugins/jquery.cluetip.js @ 16077

Last change on this file since 16077 was 9553, checked in by patdenice, 13 years ago

bug:2214
Update jQuery to 1.5.1 and cluetip to 1.0.7.
Now cluetip work on IE9.

  • Property svn:eol-style set to LF
File size: 23.4 KB
Line 
1/*
2 * jQuery clueTip plugin
3 * Version 1.0.7  (January 28, 2010)
4 * @requires jQuery v1.3+
5 *
6 * Dual licensed under the MIT and GPL licenses:
7 * http://www.opensource.org/licenses/mit-license.php
8 * http://www.gnu.org/licenses/gpl.html
9 *
10 */
11 
12/*
13 *
14 * Full list of options/settings can be found at the bottom of this file and at http://plugins.learningjquery.com/cluetip/
15 *
16 * Examples can be found at http://plugins.learningjquery.com/cluetip/demo/
17 *
18*/
19
20;(function($) { 
21  $.cluetip = {version: '1.0.6'};
22  var $cluetip, $cluetipInner, $cluetipOuter, $cluetipTitle, $cluetipArrows, $cluetipWait, $dropShadow, imgCount;
23 
24  $.fn.cluetip = function(js, options) {
25    if (typeof js == 'object') {
26      options = js;
27      js = null;
28    }
29    if (js == 'destroy') {
30      return this.removeData('thisInfo').unbind('.cluetip');
31    }
32    return this.each(function(index) {
33      var link = this, $this = $(this);
34     
35      // support metadata plugin (v1.0 and 2.0)
36      var opts = $.extend(true, {}, $.fn.cluetip.defaults, options || {}, $.metadata ? $this.metadata() : $.meta ? $this.data() : {});
37
38      // start out with no contents (for ajax activation)
39      var cluetipContents = false;
40      var cluezIndex = +opts.cluezIndex;
41      $this.data('thisInfo', {title: link.title, zIndex: cluezIndex});
42      var isActive = false, closeOnDelay = 0;
43
44      // create the cluetip divs
45      if (!$('#cluetip').length) {
46        $(['<div id="cluetip">',
47          '<div id="cluetip-outer">',
48            '<h3 id="cluetip-title"></h3>',
49            '<div id="cluetip-inner"></div>',
50          '</div>',
51          '<div id="cluetip-extra"></div>',
52          '<div id="cluetip-arrows" class="cluetip-arrows"></div>',
53        '</div>'].join(''))
54        [insertionType](insertionElement).hide();
55       
56        $cluetip = $('#cluetip').css({position: 'absolute'});
57        $cluetipOuter = $('#cluetip-outer').css({position: 'relative', zIndex: cluezIndex});
58        $cluetipInner = $('#cluetip-inner');
59        $cluetipTitle = $('#cluetip-title');       
60        $cluetipArrows = $('#cluetip-arrows');
61        $cluetipWait = $('<div id="cluetip-waitimage"></div>')
62          .css({position: 'absolute'}).insertBefore($cluetip).hide();
63      }
64      var dropShadowSteps = (opts.dropShadow) ? +opts.dropShadowSteps : 0;
65      if (!$dropShadow) {
66        $dropShadow = $([]);
67        for (var i=0; i < dropShadowSteps; i++) {
68          $dropShadow = $dropShadow.add($('<div></div>').css({zIndex: cluezIndex-1, opacity:.1, top: 1+i, left: 1+i}));
69        }
70        $dropShadow.css({position: 'absolute', backgroundColor: '#000'})
71        .prependTo($cluetip);
72      }
73      var tipAttribute = $this.attr(opts.attribute), ctClass = opts.cluetipClass;
74      if (!tipAttribute && !opts.splitTitle && !js) {
75        return true;
76      }
77      // if hideLocal is set to true, on DOM ready hide the local content that will be displayed in the clueTip
78      if (opts.local && opts.localPrefix) {tipAttribute = opts.localPrefix + tipAttribute;}
79      if (opts.local && opts.hideLocal) { $(tipAttribute + ':first').hide(); }
80      var tOffset = parseInt(opts.topOffset, 10), lOffset = parseInt(opts.leftOffset, 10);
81      // vertical measurement variables
82      var tipHeight, wHeight,
83          defHeight = isNaN(parseInt(opts.height, 10)) ? 'auto' : (/\D/g).test(opts.height) ? opts.height : opts.height + 'px';
84      var sTop, linkTop, posY, tipY, mouseY, baseline;
85      // horizontal measurement variables
86      var tipInnerWidth = parseInt(opts.width, 10) || 275,
87          tipWidth = tipInnerWidth + (parseInt($cluetip.css('paddingLeft'),10)||0) + (parseInt($cluetip.css('paddingRight'),10)||0) + dropShadowSteps,
88          linkWidth = this.offsetWidth,
89          linkLeft, posX, tipX, mouseX, winWidth;
90           
91      // parse the title
92      var tipParts;
93      var tipTitle = (opts.attribute != 'title') ? $this.attr(opts.titleAttribute) : '';
94      if (opts.splitTitle) {
95        if (tipTitle == undefined) {tipTitle = '';}
96        tipParts = tipTitle.split(opts.splitTitle);
97        tipTitle = tipParts.shift();
98      }
99      if (opts.escapeTitle) {
100        tipTitle = tipTitle.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;');
101      }
102     
103      var localContent;
104      function returnFalse() { return false; }
105
106/***************************************     
107* ACTIVATION
108****************************************/
109   
110//activate clueTip
111    var activate = function(event) {
112      if (!opts.onActivate($this)) {
113        return false;
114      }
115      isActive = true;
116      $cluetip.removeClass().css({width: tipInnerWidth});
117      if (tipAttribute == $this.attr('href')) {
118        $this.css('cursor', opts.cursor);
119      }
120      if (opts.hoverClass) {
121        $this.addClass(opts.hoverClass);
122      }
123      linkTop = posY = $this.offset().top;
124      linkLeft = $this.offset().left;
125      mouseX = event.pageX;
126      mouseY = event.pageY;
127      if (link.tagName.toLowerCase() != 'area') {
128        sTop = $(document).scrollTop();
129        winWidth = $(window).width();
130      }
131// position clueTip horizontally
132      if (opts.positionBy == 'fixed') {
133        posX = linkWidth + linkLeft + lOffset;
134        $cluetip.css({left: posX});
135      } else {
136        posX = (linkWidth > linkLeft && linkLeft > tipWidth)
137          || linkLeft + linkWidth + tipWidth + lOffset > winWidth 
138          ? linkLeft - tipWidth - lOffset 
139          : linkWidth + linkLeft + lOffset;
140        if (link.tagName.toLowerCase() == 'area' || opts.positionBy == 'mouse' || linkWidth + tipWidth > winWidth) { // position by mouse
141          if (mouseX + 20 + tipWidth > winWidth) { 
142            $cluetip.addClass(' cluetip-' + ctClass);
143            posX = (mouseX - tipWidth - lOffset) >= 0 ? mouseX - tipWidth - lOffset - parseInt($cluetip.css('marginLeft'),10) + parseInt($cluetipInner.css('marginRight'),10) :  mouseX - (tipWidth/2);
144          } else {
145            posX = mouseX + lOffset;
146          }
147        }
148        var pY = posX < 0 ? event.pageY + tOffset : event.pageY;
149        $cluetip.css({
150          left: (posX > 0 && opts.positionBy != 'bottomTop') ? posX : (mouseX + (tipWidth/2) > winWidth) ? winWidth/2 - tipWidth/2 : Math.max(mouseX - (tipWidth/2),0),
151          zIndex: $this.data('thisInfo').zIndex
152        });
153        $cluetipArrows.css({zIndex: $this.data('thisInfo').zIndex+1});
154      }
155        wHeight = $(window).height();
156
157/***************************************
158* load a string from cluetip method's first argument
159***************************************/
160      if (js) {
161        if (typeof js == 'function') {
162          js = js.call(link);
163        }
164        $cluetipInner.html(js);
165        cluetipShow(pY);
166      }
167/***************************************
168* load the title attribute only (or user-selected attribute).
169* clueTip title is the string before the first delimiter
170* subsequent delimiters place clueTip body text on separate lines
171***************************************/
172
173      else if (tipParts) {
174        var tpl = tipParts.length;
175        $cluetipInner.html(tpl ? tipParts[0] : '');
176        if (tpl > 1) {
177          for (var i=1; i < tpl; i++){
178            $cluetipInner.append('<div class="split-body">' + tipParts[i] + '</div>');
179          }         
180        }
181        cluetipShow(pY);
182      }
183/***************************************
184* load external file via ajax         
185***************************************/
186
187      else if (!opts.local && tipAttribute.indexOf('#') !== 0) {
188        if (/\.(jpe?g|tiff?|gif|png)$/i.test(tipAttribute)) {
189          $cluetipInner.html('<img src="' + tipAttribute + '" alt="' + tipTitle + '" />');
190          cluetipShow(pY);
191        } else if (cluetipContents && opts.ajaxCache) {
192          $cluetipInner.html(cluetipContents);
193          cluetipShow(pY);
194        } else {
195          var optionBeforeSend = opts.ajaxSettings.beforeSend,
196              optionError = opts.ajaxSettings.error,
197              optionSuccess = opts.ajaxSettings.success,
198              optionComplete = opts.ajaxSettings.complete;
199          var ajaxSettings = {
200            cache: false, // force requested page not to be cached by browser
201            url: tipAttribute,
202            beforeSend: function(xhr) {
203              if (optionBeforeSend) {optionBeforeSend.call(link, xhr, $cluetip, $cluetipInner);}
204              $cluetipOuter.children().empty();
205              if (opts.waitImage) {
206                $cluetipWait
207                .css({top: mouseY+20, left: mouseX+20, zIndex: $this.data('thisInfo').zIndex-1})
208                .show();
209              }
210            },
211            error: function(xhr, textStatus) {
212              if (isActive) {
213                if (optionError) {
214                  optionError.call(link, xhr, textStatus, $cluetip, $cluetipInner);
215                } else {
216                  $cluetipInner.html('<i>sorry, the contents could not be loaded</i>'); 
217                }
218              }
219            },
220            success: function(data, textStatus) {       
221              cluetipContents = opts.ajaxProcess.call(link, data);
222              if (isActive) {
223                if (optionSuccess) {optionSuccess.call(link, data, textStatus, $cluetip, $cluetipInner);}
224                $cluetipInner.html(cluetipContents);
225              }
226            },
227            complete: function(xhr, textStatus) {
228              if (optionComplete) {optionComplete.call(link, xhr, textStatus, $cluetip, $cluetipInner);}
229              var imgs = $cluetipInner[0].getElementsByTagName('img');
230              imgCount = imgs.length;
231              for (var i=0, l = imgs.length; i < l; i++) {
232                if (imgs[i].complete) {
233                  imgCount--;
234                }
235              }
236              if (imgCount && !$.browser.opera) {
237                $(imgs).bind('load error', function() {
238                  imgCount--;
239                  if (imgCount<1) {
240                    $cluetipWait.hide();
241                    if (isActive) { cluetipShow(pY); }
242                  }
243                }); 
244              } else {
245                $cluetipWait.hide();
246                if (isActive) { cluetipShow(pY); }
247              } 
248            }
249          };
250          var ajaxMergedSettings = $.extend(true, {}, opts.ajaxSettings, ajaxSettings);
251         
252          $.ajax(ajaxMergedSettings);
253        }
254
255/***************************************
256* load an element from the same page
257***************************************/
258      } else if (opts.local) {
259       
260        var $localContent = $(tipAttribute + (/#\S+$/.test(tipAttribute) ? '' : ':eq(' + index + ')')).clone(true).show();
261        $cluetipInner.html($localContent);
262        cluetipShow(pY);
263      }
264    };
265
266// get dimensions and options for cluetip and prepare it to be shown
267    var cluetipShow = function(bpY) {
268      $cluetip.addClass('cluetip-' + ctClass);
269      if (opts.truncate) { 
270        var $truncloaded = $cluetipInner.text().slice(0,opts.truncate) + '...';
271        $cluetipInner.html($truncloaded);
272      }
273      function doNothing() {}; //empty function
274      tipTitle ? $cluetipTitle.show().html(tipTitle) : (opts.showTitle) ? $cluetipTitle.show().html('&nbsp;') : $cluetipTitle.hide();
275      if (opts.sticky) {
276        var $closeLink = $('<div id="cluetip-close"><a href="#">' + opts.closeText + '</a></div>');
277        (opts.closePosition == 'bottom') ? $closeLink.appendTo($cluetipInner) : (opts.closePosition == 'title') ? $closeLink.prependTo($cluetipTitle) : $closeLink.prependTo($cluetipInner);
278        $closeLink.bind('click.cluetip', function() {
279          cluetipClose();
280          return false;
281        });
282        if (opts.mouseOutClose) {
283          $cluetip.bind('mouseleave.cluetip', function() {
284            cluetipClose();
285          });
286        } else {
287          $cluetip.unbind('mouseleave.cluetip');
288        }
289      }
290// now that content is loaded, finish the positioning
291      var direction = '';
292      $cluetipOuter.css({zIndex: $this.data('thisInfo').zIndex, overflow: defHeight == 'auto' ? 'visible' : 'auto', height: defHeight});
293      tipHeight = defHeight == 'auto' ? Math.max($cluetip.outerHeight(),$cluetip.height()) : parseInt(defHeight,10);   
294      tipY = posY;
295      baseline = sTop + wHeight;
296      if (opts.positionBy == 'fixed') {
297        tipY = posY - opts.dropShadowSteps + tOffset;
298      } else if ( (posX < mouseX && Math.max(posX, 0) + tipWidth > mouseX) || opts.positionBy == 'bottomTop') {
299        if (posY + tipHeight + tOffset > baseline && mouseY - sTop > tipHeight + tOffset) { 
300          tipY = mouseY - tipHeight - tOffset;
301          direction = 'top';
302        } else { 
303          tipY = mouseY + tOffset;
304          direction = 'bottom';
305        }
306      } else if ( posY + tipHeight + tOffset > baseline ) {
307        tipY = (tipHeight >= wHeight) ? sTop : baseline - tipHeight - tOffset;
308      } else if ($this.css('display') == 'block' || link.tagName.toLowerCase() == 'area' || opts.positionBy == "mouse") {
309        tipY = bpY - tOffset;
310      } else {
311        tipY = posY - opts.dropShadowSteps;
312      }
313      if (direction == '') {
314        posX < linkLeft ? direction = 'left' : direction = 'right';
315      }
316      $cluetip.css({top: tipY + 'px'}).removeClass().addClass('clue-' + direction + '-' + ctClass).addClass(' cluetip-' + ctClass);
317      if (opts.arrows) { // set up arrow positioning to align with element
318        var bgY = (posY - tipY - opts.dropShadowSteps);
319        $cluetipArrows.css({top: (/(left|right)/.test(direction) && posX >=0 && bgY > 0) ? bgY + 'px' : /(left|right)/.test(direction) ? 0 : ''}).show();
320      } else {
321        $cluetipArrows.hide();
322      }
323
324// (first hide, then) ***SHOW THE CLUETIP***
325      $dropShadow.hide();
326      $cluetip.hide()[opts.fx.open](opts.fx.openSpeed || 0);
327      if (opts.dropShadow) { $dropShadow.css({height: tipHeight, width: tipInnerWidth, zIndex: $this.data('thisInfo').zIndex-1}).show(); }
328      if ($.fn.bgiframe) { $cluetip.bgiframe(); }
329      // delayed close (not fully tested)
330      if (opts.delayedClose > 0) {
331        closeOnDelay = setTimeout(cluetipClose, opts.delayedClose);
332      }
333      // trigger the optional onShow function
334      opts.onShow.call(link, $cluetip, $cluetipInner);
335    };
336
337/***************************************
338   =INACTIVATION
339-------------------------------------- */
340    var inactivate = function(event) {
341      isActive = false;
342      $cluetipWait.hide();
343      if (!opts.sticky || (/click|toggle/).test(opts.activation) ) {
344        cluetipClose();
345        clearTimeout(closeOnDelay);       
346      }
347      if (opts.hoverClass) {
348        $this.removeClass(opts.hoverClass);
349      }
350    };
351// close cluetip and reset some things
352    var cluetipClose = function() {
353      $cluetipOuter 
354      .parent().hide().removeClass();
355      opts.onHide.call(link, $cluetip, $cluetipInner);
356      $this.removeClass('cluetip-clicked');
357      if (tipTitle) {
358        $this.attr(opts.titleAttribute, tipTitle);
359      }
360      $this.css('cursor','');
361      if (opts.arrows) {
362        $cluetipArrows.css({top: ''});
363      }
364    };
365
366    $(document).bind('hideCluetip', function(e) {
367      cluetipClose();
368    });
369/***************************************
370   =BIND EVENTS
371-------------------------------------- */
372  // activate by click
373      if ( (/click|toggle/).test(opts.activation) ) {
374        $this.bind('click.cluetip', function(event) {
375          if ($cluetip.is(':hidden') || !$this.is('.cluetip-clicked')) {
376            activate(event);
377            $('.cluetip-clicked').removeClass('cluetip-clicked');
378            $this.addClass('cluetip-clicked');
379          } else {
380            inactivate(event);
381          }
382          this.blur();
383          return false;
384        });
385  // activate by focus; inactivate by blur   
386      } else if (opts.activation == 'focus') {
387        $this.bind('focus.cluetip', function(event) {
388          activate(event);
389        });
390        $this.bind('blur.cluetip', function(event) {
391          inactivate(event);
392        });
393  // activate by hover
394      } else {
395        // clicking is returned false if clickThrough option is set to false
396        $this[opts.clickThrough ? 'unbind' : 'bind']('click', returnFalse);
397        //set up mouse tracking
398        var mouseTracks = function(evt) {
399          if (opts.tracking == true) {
400            var trackX = posX - evt.pageX;
401            var trackY = tipY ? tipY - evt.pageY : posY - evt.pageY;
402            $this.bind('mousemove.cluetip', function(evt) {
403              $cluetip.css({left: evt.pageX + trackX, top: evt.pageY + trackY });
404            });
405          }
406        };
407        if ($.fn.hoverIntent && opts.hoverIntent) {
408          $this.hoverIntent({
409            sensitivity: opts.hoverIntent.sensitivity,
410            interval: opts.hoverIntent.interval, 
411            over: function(event) {
412              activate(event);
413              mouseTracks(event);
414            }, 
415            timeout: opts.hoverIntent.timeout, 
416            out: function(event) {inactivate(event); $this.unbind('mousemove.cluetip');}
417          });           
418        } else {
419          $this.bind('mouseenter.cluetip', function(event) {
420            activate(event);
421            mouseTracks(event);
422          })
423          .bind('mouseleave.cluetip', function(event) {
424            inactivate(event);
425            $this.unbind('mousemove.cluetip');
426          });
427        }
428        $this.bind('mouseover.cluetip', function(event) {
429          $this.attr('title','');
430        }).bind('mouseleave.cluetip', function(event) {
431          $this.attr('title', $this.data('thisInfo').title);
432        });
433      }
434    });
435  };
436 
437/*
438 * options for clueTip
439 *
440 * each one can be explicitly overridden by changing its value.
441 * for example: $.fn.cluetip.defaults.width = 200;
442 * would change the default width for all clueTips to 200.
443 *
444 * each one can also be overridden by passing an options map to the cluetip method.
445 * for example: $('a.example').cluetip({width: 200});
446 * would change the default width to 200 for clueTips invoked by a link with class of "example"
447 *
448 */
449 
450  $.fn.cluetip.defaults = {  // set up default options
451    width:            275,      // The width of the clueTip
452    height:           'auto',   // The height of the clueTip
453    cluezIndex:       97,       // Sets the z-index style property of the clueTip
454    positionBy:       'auto',   // Sets the type of positioning: 'auto', 'mouse','bottomTop', 'fixed'
455    topOffset:        15,       // Number of px to offset clueTip from top of invoking element
456    leftOffset:       15,       // Number of px to offset clueTip from left of invoking element
457    local:            false,    // Whether to use content from the same page for the clueTip's body
458    localPrefix:      null,       // string to be prepended to the tip attribute if local is true
459    hideLocal:        true,     // If local option is set to true, this determines whether local content
460                                // to be shown in clueTip should be hidden at its original location
461    attribute:        'rel',    // the attribute to be used for fetching the clueTip's body content
462    titleAttribute:   'title',  // the attribute to be used for fetching the clueTip's title
463    splitTitle:       '',       // A character used to split the title attribute into the clueTip title and divs
464                                // within the clueTip body. more info below [6]
465    escapeTitle:      false,    // whether to html escape the title attribute
466    showTitle:        true,     // show title bar of the clueTip, even if title attribute not set
467    cluetipClass:     'default',// class added to outermost clueTip div in the form of 'cluetip-' + clueTipClass.
468    hoverClass:       '',       // class applied to the invoking element onmouseover and removed onmouseout
469    waitImage:        true,     // whether to show a "loading" img, which is set in jquery.cluetip.css
470    cursor:           'help',
471    arrows:           false,    // if true, displays arrow on appropriate side of clueTip
472    dropShadow:       true,     // set to false if you don't want the drop-shadow effect on the clueTip
473    dropShadowSteps:  6,        // adjusts the size of the drop shadow
474    sticky:           false,    // keep visible until manually closed
475    mouseOutClose:    false,    // close when clueTip is moused out
476    activation:       'hover',  // set to 'click' to force user to click to show clueTip
477                                // set to 'focus' to show on focus of a form element and hide on blur
478    clickThrough:     false,    // if true, and activation is not 'click', then clicking on link will take user to the link's href,
479                                // even if href and tipAttribute are equal
480    tracking:         false,    // if true, clueTip will track mouse movement (experimental)
481    delayedClose:     0,        // close clueTip on a timed delay (experimental)
482    closePosition:    'top',    // location of close text for sticky cluetips; can be 'top' or 'bottom' or 'title'
483    closeText:        'Close',  // text (or HTML) to to be clicked to close sticky clueTips
484    truncate:         0,        // number of characters to truncate clueTip's contents. if 0, no truncation occurs
485   
486    // effect and speed for opening clueTips
487    fx: {             
488                      open:       'show', // can be 'show' or 'slideDown' or 'fadeIn'
489                      openSpeed:  ''
490    },     
491
492    // settings for when hoverIntent plugin is used             
493    hoverIntent: {   
494                      sensitivity:  3,
495                                  interval:     50,
496                                  timeout:      0
497    },
498
499    // short-circuit function to run just before clueTip is shown.
500    onActivate:       function(e) {return true;},
501    // function to run just after clueTip is shown.
502    onShow:           function(ct, ci){},
503    // function to run just after clueTip is hidden.
504    onHide:           function(ct, ci){},
505    // whether to cache results of ajax request to avoid unnecessary hits to server   
506    ajaxCache:        true, 
507
508    // process data retrieved via xhr before it's displayed
509    ajaxProcess:      function(data) {
510                        data = data.replace(/<(script|style|title)[^<]+<\/(script|style|title)>/gm, '').replace(/<(link|meta)[^>]+>/g,'');
511                        return data;
512    },               
513
514    // can pass in standard $.ajax() parameters. Callback functions, such as beforeSend,
515    // will be queued first within the default callbacks.
516    // The only exception is error, which overrides the default
517    ajaxSettings: {
518                      // error: function(ct, ci) { /* override default error callback */ }
519                      // beforeSend: function(ct, ci) { /* called first within default beforeSend callback }
520                      dataType: 'html'
521    },
522    debug: false
523  };
524
525
526/*
527 * Global defaults for clueTips. Apply to all calls to the clueTip plugin.
528 *
529 * @example $.cluetip.setup({
530 *   insertionType: 'prependTo',
531 *   insertionElement: '#container'
532 * });
533 *
534 * @property
535 * @name $.cluetip.setup
536 * @type Map
537 * @cat Plugins/tooltip
538 * @option String insertionType: Default is 'appendTo'. Determines the method to be used for inserting the clueTip into the DOM. Permitted values are 'appendTo', 'prependTo', 'insertBefore', and 'insertAfter'
539 * @option String insertionElement: Default is 'body'. Determines which element in the DOM the plugin will reference when inserting the clueTip.
540 *
541 */
542   
543  var insertionType = 'appendTo', insertionElement = 'body';
544
545  $.cluetip.setup = function(options) {
546    if (options && options.insertionType && (options.insertionType).match(/appendTo|prependTo|insertBefore|insertAfter/)) {
547      insertionType = options.insertionType;
548    }
549    if (options && options.insertionElement) {
550      insertionElement = options.insertionElement;
551    }
552  };
553 
554})(jQuery);
Note: See TracBrowser for help on using the repository browser.