Description
This script allows you to create a more unique, designed tooltip (popup) when you hover over a particular element. As we hover over the targeted element, the script creates a div which contains the necessary info. When we mouseout, the script removes the div and thus, the tooltip goes away.
Currently, the info in the tooltip is essentially hard-coded in the script, but a more advanced usage may be to call and display info from a database to generate dynamic tooltips/previews.
See this similar example to create an image preview as you hover an image thumbnail or some other targeted element.
Demo
Hover over me to view a cool tooltip!
The Code:
HTML
<p><a>Hover over me to view a cool tooltip!</a></p>
CSS
#container {
width: 400px;
margin: auto;
margin-top: 5em;
}
#info {
background: #7F7777;
width: 300px;
padding-bottom: .5em;
overflow: hidden;
position: absolute;
}
h5 {
padding: .4em 1em;
margin: 0 0 .5em 0;
background: #292929;
color: #9F9F9F;
border-bottom: 1px solid #BFBFBF;
border-top: 1px solid black;
}
#info p {
color: #fff;
margin-left: 15px;
margin-top: 0;
padding: 0 0 0 2em;
}
jQuery
<script type="text/javascript" charset="utf-8">
$(function() {
$('a').hover(function(e) { // function that runs when the user hovers their mouse over an anchor tag
var html = '<div id="info">'; // creates html of a div with id = info and stores that in a variable called html
html += '<h5>Some Title Would Go Right Here</h5>'; // this += takes what is stored in the variable html and appends something to it, in this case, an h4
html += '<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>';
html += '</div>'; // closes the div we opened above
$('body').append(html).children('#info').hide().fadeIn(400); // appends the contents of the variable html to the body markup. We are getting the children of the variable html, specifically the div with id of info, and hiding that div. Then we are able to have it fade in on mousover.
$('#info').css('top', e.pageY + -20).css('left', e.pageX + 40); // offsets the preview by 40px to the righ, and -20px from the top of your mouse
}, function() {
$('#info').remove(); // removes info div when you stop hovering
});
$('a').mousemove(function(e) {
$('#info').css('top', e.pageY + -20).css('left', e.pageX + 40); // resets values when the mouse moves
});
});
</script>
