I've created a simple plugin following tuts+ and modified it to do what I want. It basically creates a "tooltip" that I am trying to leave visible for a certain amount of time but also allow the user to click on the block so more of a notification than a tool tip. What I have so far is below, but when it doesn't auto hide...on click to close work however. Can anyone spot what I'm doing wrong/improvements?
$.fn.betterTooltip = function(options){
/* Setup the options for the tooltip that can be
accessed from outside the plugin */
var defaults = {
speed: 200,
delay: 300,
hideAfter:5000
};
var options = $.extend(defaults, options);
/* Create a function that builds the tooltip
markup. Then, prepend the tooltip to the body */
getTip = function() {
var tTip =
"<div class='tip'>" +
"<div class='tipMid'>" +
"</div>" +
"<div class='tipBtm'></div>" +
"</div>";
return tTip;
}
$("body").prepend(getTip());
/* Give each item with the class associated with
the plugin the ability to call the tooltip */
$(this).each(function(){
var $this = $(this);
var tip = $('.tip');
var tipInner = $('.tip .tipMid');
var tTitle = (this.title);
this.title = "";
var offset = $(this).offset();
var tLeft = offset.left;
var tTop = offset.top;
var tWidth = $this.width();
var tHeight = $this.height();
/* Delay the fade-in animation of the tooltip */
setTimer = function() {
$this.showTipTimer = setInterval("showTip()", defaults.delay);
}
hideTip=function(){
stopTimer();
tip.hide();
}
stopTimer = function() {
clearInterval($this.showTipTimer);
clearInterval( $this.hideTimer);
}
/* Position the too开发者_如何学Pythonltip relative to the class
associated with the tooltip */
setTip = function(top, left){
var topOffset = tip.height()-30;
var xTip = (left+60)+"px";
var yTip = (top-topOffset)+"px";
tip.css({
'top' : yTip,
'left' : xTip
});
}
/* This function stops the timer and creates the
fade-in animation */
showTip = function(){
stopTimer();
tip.animate({
"top": "+=20px",
"opacity": "toggle"
}, defaults.speed);
}
$(this).ready(function() {
tipInner.html(tTitle+'<br />(Click to dismiss)');
setTip(tTop, tLeft);
setTimer();
hideTimer=function(){
$this.hideTimer=setInterval("hideTip()",defaults.hideAfter);
}
hideTimer();
});
$(tip).click(function() {
hideTip();
});
});
};
I think you want setTimeout
and clearTimeout
instead of the ...Interval
versions you have. The former fire their callbacks once, whereas the latter do it repeatedly.
Some tips:
- Don't pass a string to
setTimeout
orsetInterval
for the code to run - use a function pointer. I find it's much less error prone and scoping is never an issue. - Hide the tip on a
mouseleave
event (either from the item that the tip is for or the tip itself), and show it onmouseover
ormouseenter
. This is more efficient than having javascript running all the time.
精彩评论