Problems with jquery.attr ()

I wrote this quick tip 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 header because both of them are stupid. I know that I should go something like this:

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

The problem is that I cannot add it back. I tried:

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

but it failed. Suggestions?

+3
source share
2 answers

The value stored in the variable titleis local to this function and is lost after the function is executed in any case.

One solution would be to keep the previous title in the element data().

var $th = $(this);

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

Then access it when you need it (presumably in the next function for freezing).

var $th = $(this);

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

You can bring a 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();
});

... , data() .

+6

title . , .

+2

Source: https://habr.com/ru/post/1752967/


All Articles