JQuery Tooltip

by janetyc

HTML

<h1>Easy Tooltip Using jQuery</h1>
    
<p><input title="Web Standards Magazine">Roll over for tooltip</input></p>
<p><textarea title="Easiest jQuery Tooltip">go back</textarea> to the article</p>

CSS

body {
    margin:0;
    padding:40px;
    background:#fff;
    font:80% Arial, Helvetica, sans-serif;
    color:#555;
    line-height:180%;
}

h1{
    font-size:180%;
    font-weight:normal;
    color:#555;
}
a{
    text-decoration:none;
    color:#f30;    
}
p{
    clear:both;
    margin:0;
    padding:.5em 0;
}
pre{
    display:block;
    font:100% "Courier New", Courier, monospace;
    padding:10px;
    border:1px solid #bae2f0;
    background:#e3f4f9;    
    margin:.5em 0;
    overflow:auto;
    width:800px;
}


/*  */

#tooltip{
    position:absolute;
    border:1px solid #333;
    background:#f7f5d1;
    padding:2px 5px;
    color:#333;
    display:none;
    }

JavaScript

function getSelectedText() {
    if (window.getSelection) return window.getSelection().toString();
    else if (document.getSelection) return document.getSelection();
    else if (document.selection) return document.selection.createRange().text;
}


tooltip = function(){    
    
    xOffset = 10;
    yOffset = 20;        
              
    $("input").each(function(e){
        $(this).addClass("tooltip");
    });

    
    $(".tooltip").hover(function(e){                                              
        this.t = this.title;
        this.title = "";                                      
        $("body").append("<p id='tooltip'>"+ this.t +"</p>");
        $("#tooltip")
            .css("top",(e.pageY - xOffset) + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn(5);        
    },
    function(){
        this.title = this.t;        
        $("#tooltip").remove();
    });    
    $(".tooltip").mousemove(function(e){
        $("#tooltip")
            .css("top",(e.pageY - xOffset) + "px")
            .css("left",(e.pageX + yOffset) + "px");
    });            
};



// starting the script on page load
$(document).ready(function(){
    tooltip();

});