Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery .attr() problems

Tags:

jquery

attr

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?

like image 670
andrei Avatar asked Jun 30 '26 10:06

andrei


2 Answers

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.

like image 118
user113716 Avatar answered Jul 02 '26 01:07

user113716


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.

like image 38
Adrian Godong Avatar answered Jul 02 '26 03:07

Adrian Godong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!