Pass variable from hover to departure

http://jsfiddle.net/MwQbE/

I have jQuery Below, but I can not get the variables to go to the second function

$("img").hover(function(){
    var $image = $(this);
    var $imageNowWidth = $image.width();
},function() {
    // get variable value for $image and $imageNowWidth   
});​

When testing on jsFiddle it does not work, what can I do to pass a variable to a second function?

+3
source share
4 answers

Just define those 2 variables outside .hover, and then you can use them inside the mouseleave function. See below,

var $image, $imageNowWidth;
$("img").hover(function(){ //mouseenter
   $image = $(this);
   $imageNowWidth = $image.width();
},function() {            //mouseleave
    //$image and $imageNowWidth is accessible HERE
});​

I just want to clarify what thiswill be available inside the function mouseleaveso that you can do the same or more we do what you do insidemouseenter

+4
source

Define getterboth setterfor imageand imageNoWidth, as shown below,

var getImage, getImageNoWidth;
$("img").hover(function(){
   $image = $(this);
   $imageNowWidth = $image.width();
    getImage = function(){
        return $image;
    };
    getImageNoWidth = function(){
        return $imageNowWidth;
    };
},function() {
    // get variable value for $image (getImage()) and $imageNowWidth (getImageNoWidth())
}
+2

, .

var image;
var imageNowWidth;
$("img").hover(function(){
    image = $(this);
    imageNowWidth = $image.width();
},function() {
    // get variable value for $image and $imageNowWidth   
});​
+1

Store the variable directly on the jquery object using the jquery 'data' method:

$("img").hover(function(){
    var $image = $(this);
    $image.data('imageNowWidth',$image.width());
},function() {
    var previousImageWidth = $(this).data('imageNowWidth');
    // do whatever you want to do with the width       
});​
+1
source

All Articles