Skip to content

Instantly share code, notes, and snippets.

@aviddiviner
Last active August 29, 2015 13:56
Show Gist options
  • Save aviddiviner/8907046 to your computer and use it in GitHub Desktop.
Save aviddiviner/8907046 to your computer and use it in GitHub Desktop.
A delayed reaction tooltip handler for jQuery
// A delayed reaction tooltip handler for jQuery.
// Useful for tooltips that are costly to load, such as images.
//
// $('#article a').delayedHint(function(anchor, callback) {
// var imgSrc = $(anchor).attr('href');
// $('<img/>').load(function() {
// var frame = $('<span class="frame"></span>').append(this);
// callback(frame);
// }).attr('src', imgSrc);
// });
$.fn.delayedHint = function(loadCallback, config) {
var defaults = {
hoverDelay: 400, // Milliseconds
cssClass: 'hint',
showCallback: function(el, posX, posY) {
var d = $(document);
$(el).css('top', Math.min(posY, d.height() - el.height()));
$(el).css('left', Math.min(posX, d.width() - el.width()));
$(el).show();
},
hideCallback: function(el) {
$(el).hide();
}
};
var opts = $.extend({}, defaults, config);
var hoveringOn;
var delayTimer;
this.each(function() {
var self = $(this);
var hoverIn = function(ev) {
var hints = self.children('span.' + opts.cssClass);
if (hints.length > 0) {
opts.showCallback(hints, ev.pageX, ev.pageY);
} else {
// No hint yet; load it if we stick around for a few millis
hoveringOn = self;
delayTimer = setTimeout(function() {
// Cool, we're good to load, so attach the empty hint for now
var hint = $('<span class="' + opts.cssClass + '"></span>').appendTo(self);
loadCallback(self, function(el) {
el.appendTo(hint);
if (self == hoveringOn) {
// Now show the hint if we're still hovering on
opts.showCallback(hint, ev.pageX, ev.pageY);
}
});
}, opts.hoverDelay);
}
}
var hoverOut = function(ev) {
hoveringOn = null;
clearTimeout(delayTimer); // Drop the hint from loading
var hints = self.children('span.' + opts.cssClass);
opts.hideCallback(hints);
}
self.hover(hoverIn, hoverOut);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment