Hover Tooltips

After SO revision

by someprimetime

HTML

<div class="wrapper">
    <a href="#" class="js-tooltip" alt="You just hovered over for information">Hover over me</a>
</div>
<div class="wrapper_2">
    <a href="#" class="js-tooltip" alt="This is a second demo">Hover over me too!</a>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" class="js-tooltip" alt="This is a third demo">i wrap but it centers</a><br />
    <a href="#" class="js-tooltip" alt="<script>alert('yo');</script>">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: 400px;
    position: absolute;
    z-index: 300;
}
.tooltip_arrow {
    background: url(http://i.imgur.com/K5ynr.png) no-repeat;
    width: 9px;
    height: 5px;
    position: absolute;
    top: 21px;
    z-index: 300;
}
.wrapper {
    display:block;
    position: relative;
    top: 100px;
    left: 50px;
    width: 80px;
}
.wrapper_2 {
    display:block;
    position: relative;
    top: 100px;
    left: 75px;
    margin: .3em;
    width: 100px;
}

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');
                    $altText = toolTip.escape($altText);
                    var $parentWidth = $that.outerWidth(true);
                    var $pos = $that.offset();
                    var $tip = $toolSpan.clone(true);

                    $that.parent().after($tip);
                    $tip.prepend($altText);
                    $that.parent().next($tip).css({
                        top: $pos.top - 30,
                        left: $pos.left + ($that.width() / 2) - ($tip.outerWidth(true) / 2)
                    }).fadeIn(100);
                    $(".tooltip_arrow", $that.parent().next()).css({
                        left: ($tip.outerWidth(true) / 2)
                    }).fadeIn(100);
                }).mouseout(function() {
                    $that.parent().next().fadeOut(100).remove();
                });
            });
        },
        /* end init */

        escape: function(str) {
            return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        }
    };
    $.fn.toolTip = toolTip.init;
})(jQuery);
$(function() {
    $('.js-tooltip').toolTip();
});