This is my second jQuery script: a universal tooltip for my entire web page. It took me a couple of days to research and make it work.
Now, I need help from the experts to optimize my newbie code.
This is one of the ways I can show the tooltip:
<a class="tooltip" data-tooltip="this is the text for my tooltip" href="#">My tooltip</a>
jQuery:
$('.tooltip').hover(function(){
var text = $(this).attr('data-tooltip');
// get coordinates (top, left) of clicked element
var offset = $(this).offset();
// append tooltip to body, hide it, insert text
// center the tooltip to the clicked element and display it 3 pixels above the clicked element
$('<p class="tooltipbox"></p>')
.hide()
.text(text)
.appendTo('body')
.css("left", offset.left - (($(".tooltipbox").outerWidth() - $(this).width()) / 2 )) // center the tooltip
.css("top", offset.top - $(".tooltipbox").outerHeight() - 3)
.fadeIn(200);
}, function() {
// hover out the tooltip box
$('.tooltipbox').remove();
});
Something simple that works ok. Any way to improve my second jQuery script?