Skip to content

Instantly share code, notes, and snippets.

@fabioyamate
Created November 22, 2013 13:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioyamate/7599504 to your computer and use it in GitHub Desktop.
Save fabioyamate/7599504 to your computer and use it in GitHub Desktop.
A simple lib to create popup/tooltips
(function(window, $) {
var containers = [];
// Public: position a container overlayed close to the target
//
// container - the container id
// callback - a function callback that receives 'container' and 'target'
//
// Examples
//
// var handler = overlay('#my-container', function(container, target) {
// var $target = $(target);
// $(container).text($target.attr('rel'));
// });
//
// // binding the handler to an event
// $('target-element').click(handler);
//
// Returns a handler to bind in an event in order to
// position the container close to the target.
function overlay(container, callback) {
var $container = $(container);
// use noop function if undefined
callback = callback || $.noop;
containers.push($container);
// Private: Calculates the position offset for container,
// based on target position.
//
// target - the reference element to be positioned with
//
// Returns the container aligned at the right of the target element
function setupContainerPosition(element) {
var target = $(element),
offset = target.offset(),
height = target.outerHeight(),
width = target.outerWidth(),
attributes = { top: offset.top + height, left: offset.left + width - $container.outerWidth() };
if (target.data('orientation') === 'LR') {
attributes.left = offset.left;
}
$container.css(attributes);
}
// Private: calculates the proper position of the overlay
// and turns it visible
function show() {
setupContainerPosition(this);
$container.addClass('visible');
}
return function() {
overlay.hide();
$.when(callback($container, this)).then($.proxy(show, this));
return false;
};
}
// Private: hide all other defined containers
// so we don't end up with two different overlays
// present on screen.
function hideAllContainers() {
$.each(containers, function() {
this.removeClass('visible').trigger('overlay:closed');
});
}
// Public: jQuery entrypoint to use the 'overlay' function
//
// Example
// $('target-element').overlay('#container-id', function(container, target) {
// var $target = $(target);
// $(container).text($target.attr('rel'));
// });
//
// Returns the jQuery element.
$.fn.overlay = function(container, callback) {
var handler = overlay(container, callback);
return this.each(function() {
$(this).bind('click', handler);
});
};
$(window).on('overlay:close', function() {
overlay.hide();
});
overlay.hide = hideAllContainers;
window.overlay = overlay;
})(window, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment