Skip to content

Instantly share code, notes, and snippets.

@iammerrick
Created March 17, 2011 22:04
Show Gist options
  • Save iammerrick/875224 to your computer and use it in GitHub Desktop.
Save iammerrick/875224 to your computer and use it in GitHub Desktop.
Basic tooltip like plugin.
$.fn.bubble = function(options){
/* Initialize base variables */
var settings = {
offset : {
left: 0,
top: 0
},
action: 'click' // Event to toggle bubble
},
settings = $.extend(settings, options), // Merge user passed options with defaults
el = $(this), // Store reference to plugin element
bubble = $(el.attr('data-bubble')); // Grab plugin element bubble content from el[data-bubble=css-selector-of-bubble]
/* Intialize base CSS for the bubble. */
bubble.css({
'position': 'absolute',
'display' : 'none'
});
$(this).bind(settings.action, toggleBubble); // Bind event to toggle bubble
$(window).bind('resize', positionBubble).trigger('resize'); // Bind resize to reposition the bubble, and fire it once for initialization
/* Toggle the bubble on and off */
function toggleBubble(event){
bubble.fadeToggle();
}
/* Position the bubble using the offsets based off the current position of el */
function positionBubble(event){
var position = el.position(),
left = (position.left + settings.offset.left),
top = (position.top + settings.offset.top);
/* If the pass the string center or middle do some math, measure both el and bubble and line them up horizontally. */
if(settings.offset.left === 'center' || settings.offset.left === 'middle'){
left = ((position.left - (bubble.width() / 2)) + (el.width() / 2));
}
bubble.css({
'left' : left,
'top' : top
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment