/
i have the jQuery Below but i cant get the variables to pass 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 doesn't work, what can I do to pass the variable to the second function?
http://jsfiddle/MwQbE/
i have the jQuery Below but i cant get the variables to pass 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 doesn't work, what can I do to pass the variable to the second function?
Share Improve this question asked May 18, 2012 at 18:37 Yusaf KhaliqYusaf Khaliq 3,39311 gold badges45 silver badges82 bronze badges 1- Just declare them in the second function as well. – Diodeus - James MacFarlane Commented May 18, 2012 at 18:38
4 Answers
Reset to default 4Simply define those 2 variables outside .hover
and then you can use them inside mouseleave function. See below,
var $image, $imageNowWidth;
$("img").hover(function(){ //mouseenter
$image = $(this);
$imageNowWidth = $image.width();
},function() { //mouseleave
//$image and $imageNowWidth is accessible HERE
});
Just want to clarify that this
will be available inside mouseleave
function so you can do the same or more w.e you are doing inside mouseenter
Define getter
and setter
for image
and imageNoWidth
as 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())
}
Declare the variable outside, so it is accessible in both functions.
var image;
var imageNowWidth;
$("img").hover(function(){
image = $(this);
imageNowWidth = $image.width();
},function() {
// get variable value for $image and $imageNowWidth
});
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
});