tags:

views:

32

answers:

2

I wrote this quick tooltip function for my links:

$(function() {
  $('a').hover(function(e) {
    var title = $(this).attr('title');
    $('<div id="tooltip">' + title + '</div>').css({"top" : e.pageY + 12, "left" : e.pageX + 12}).appendTo('body');
  }, function() {
    $('#tooltip').remove();
  });

  $('a').mousemove(function(e){ 
    $('#tooltip').css({"top" : e.pageY + 12, "left" : e.pageX + 12});
  })
});

I want to remove the original title because having both is stupid. I know I should go something like this:

$('a').hover(function() {
  $(this).attr('title', '');
});

The problem is that I can't add it back. I tried:

$(this).attr('title', title) //from my title variable

but it failed. Suggestions?

+3  A: 

The value stored in title variable is local to that function, and is lost after the function is done executing anyway.

One solution would be to store the previous title in the element's data().

var $th = $(this);

$th.data( 'prevTitle', $th.attr('title') );

Then access it when you need it (presumably in your next function for hover).

var $th = $(this);

$th.attr('title', $th.data( 'prevTitle' ));

You could bring the variable declaration outside of both functions.

var title;

$('a').hover(function(e){
     title = $(this).attr('title');
     $('<div id="tooltip">' + title + '</div>').css({"top" : e.pageY + 12, "left" : e.pageX + 12}).appendTo('body');
}, function(){
    $th.attr('title', title);
    $('#tooltip').remove();
});

...but I think using data() would be safer.

patrick dw
The variable declaration outside of both functions is the way to go.
Gert G
@Gert G @patricki used the outside declaration of a var and it works just fine. thx.
andrei
@Gert - You may be right, but somehow I feel better about having the information tied to the element, even though it is a little less efficient. Irrational, perhaps. :o)
patrick dw
@patrick - Well, it works either way. Good answer.
Gert G
+1  A: 

Your title variable only exist in the scope of the first handler. You will have to store the value somewhere else accessible from the second handler.

Adrian Godong
thank you. i wasn't aware that i lose that variable. i simple made a new one and now it works :)
andrei