Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery hover pass variable to callback function

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);

});
like image 286
Brian Barthold Avatar asked Jun 09 '10 18:06

Brian Barthold


2 Answers

$(".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.

like image 56
Matrym Avatar answered Sep 16 '22 21:09

Matrym


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);

});
like image 36
gabriev82 Avatar answered Sep 20 '22 21:09

gabriev82