I have a function for creating a tooltip from a title. I am trying to wrap this function in an if statement that checks the title length before returning the tooltip. But it doesn’t seem to want to return anything. Is there a better way to do this then with an if statement?
$(document).ready(function() {
if ($('#menu-headermenu a').attr('title').length == 0) {
return null;
} else {
//Select all anchor tag with rel set to tooltip
$('#menu-headermenu a').mouseover(function(e) {
//Grab the title attribute's value and assign it to a variable
var tip = $(this).attr('title');
//Remove the title attribute's to avoid the native tooltip from the browser
$(this).attr('title','');
//Append the tooltip template and its value
$(this).append('<div id="tooltip"><p>Take me to:<p><div class="tooltipcontent"' + tip + '</div></div>');
//Set the X and Y axis of the tooltip
$('#tooltip').css('top', e.pageY + 10 );
$('#tooltip').css('left', e.pageX + 20 );
//Show the tooltip with faceIn effect
$('#tooltip').fadeIn('500');
$('#tooltip').fadeTo('10',0.8);
}).mousemove(function(e) {
//Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
$('#tooltip').css('top', e.pageY + 10 );
$('#tooltip').css('left', e.pageX + 20 );
}).mouseout(function() {
//Put back the title attribute's value
$(this).attr('title',$('div.tooltipcontent').html());
//Remove the appended tooltip template
$(this).children('div#tooltip').remove();
});
}
});
Have you considered using existing solutions? (e.g. http://jquery.bassistance.de/tooltip/demo/)
As for your question, you can just add a filter to your selector:
$('#menu-headermenu a[title]')This should make it so that only elements with a title attribute will have the events attached.