7

I am trying to remove a title attribute for a link on hover and then add it back on mouse out. I would like to pass var hoverText to the hover out...

Here is the code I have. Any ideas?

$(".icon a").hover(function() {
  $this = $(this);
  var hoverText = $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function(hoverText) {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", hoverText);

});

2 Answers 2

6
$(".icon a").hover(function() {
  $this = $(this);
  $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function(hoverText) {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", $.data(this, 'title');

});

The trick is:

$.data(this, 'title');

When you use data, you're effectively storing the variable on that dom element for the express purpose you've just described. You could also solve the problem by declaring the $this variable above your initial hover function, expanding the scope to cover both.

Sign up to request clarification or add additional context in comments.

2 Comments

that is what I have been trying to figure out how to declare it above this? any thoughts?
Exactly what I was looking for. This works great for doing simple tooltips. Append the tooltip markup to <body> in the first function, store the DOM object in a variable, store that variable in the $.data object, access it in the second function to fade it out.
1

Put "hoverText" as global variable.

var hoverText = '';
$(".icon a").hover(function() {
  $this = $(this);
  hoverText = $.data(this, 'title', $this.attr('title'));                             
  $(this).find("em").animate({opacity: "show", top: "-35"}, "slow");
  $(this).find("em").text(hoverText);       

  $this.removeAttr('title');       


}, function() {             

  $(this).find("em").animate({opacity: "hide", top: "-45"}, "fast");     
  $(this).attr("title", hoverText);

});

2 Comments

this works but i want to stay away from global variables any thoughts?
Thats a flipping terrible solution... When Assigning hovers that variable is definitely not going to stay the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.