Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top