hover tooltip

by someprimetime

HTML

<div class="wrapper">
    <a href="#" class="js-tooltip" alt="You just hovered over for information">Hover over me</a>
</div>

CSS

body {
    font-family: helvetica, arial;
    font-size: 11px;
}
.tooltip {
    background: #000;
    display: none;
    color: #fff;
    padding: 4px;
    border-radius: 4px;
    position: absolute;
    z-index: 300;
}
.tooltip_arrow {
    background: url(http://i.imgur.com/K5ynr.png) no-repeat;
    width: 9px;
    height: 5px;
    position: absolute;
    top: 20px;
    z-index: 300;
}
.wrapper {
    display:block;
    position: relative;
    top: 100px;
    left: 50px;
    width: 80px;
}

JavaScript

(function($) {
    var toolTip = {
        init: function() {
            this.each(function() {
                var $that = $(this);
                // our boolean object to check if it already exists on the page
                var $toolSpan = $('<div class="tooltip"><span class="tooltip_arrow"></span></div>');

                var preloadImages = function() {
                    var tempImage = new Image();
                    tempImage.src = 'http://i.imgur.com/K5ynr.png';
                    tempImage = null;
                };
                preloadImages();
                $that.mouseover(function() {
                    var $altText = $that.attr('alt');
                    var $parentWidth = $that.parent().width();
                    var $parentPos = $that.parent().position();
                    var $parentPosY = $parentPos.top;
                    var $parentPosX = $parentPos.left;
                    
                        $that.parent().after($toolSpan);
                        $toolSpan.prepend($altText);
                        $that.parent().next($toolSpan).css('top', $parentPosY - 30).css('left', $parentPosX).fadeIn();

                        var $toolSpanWidth = $that.parent().width();
                        $that.parent().next('.tooltip').children('.tooltip_arrow').css('left', $toolSpanWidth / 2).fadeIn();
                }).mouseout(function() {
                    $that.parent().next($toolSpan).text('').hide().remove();
                });
            });
        } /* end init */
    };
    $.fn.toolTip = toolTip.init;
})(jQuery);

$(function() {
    $('.js-tooltip').toolTip();
});