I am using the following code to swap an image src out on hover of the child's parent. How can I save the original source in a variable and on hover off return the image to its original source?
$("#parent span").hover(function(){
var currentImage = $('img', this ).attr("src","images/orbs/yellowBar.png");
$('img', this ).attr("src","images/yellowBar.png");
},function(){
$('img', this ).attr("src",currentImage);
});
I am using the following code to swap an image src out on hover of the child's parent. How can I save the original source in a variable and on hover off return the image to its original source?
$("#parent span").hover(function(){
var currentImage = $('img', this ).attr("src","images/orbs/yellowBar.png");
$('img', this ).attr("src","images/yellowBar.png");
},function(){
$('img', this ).attr("src",currentImage);
});
Share
Improve this question
asked Apr 9, 2015 at 17:56
nicknick
1,2563 gold badges21 silver badges41 bronze badges
1
- 2 Try saving it to a global variable. so, outside of that function. – Steve Commented Apr 9, 2015 at 17:58
5 Answers
Reset to default 3Define currentImage
outside of your function:
var currentImage;
$("#parent span").hover(function() {
currentImage = $('img', this).attr("src", "images/orbs/yellowBar.png");
$('img', this).attr("src", "images/yellowBar.png");
}, function() {
$('img', this).attr("src", currentImage);
});
As for me, the better way is to create two css classes with different background image and don't use javascript/jquery for image switch on hover at all.
css:
.time-stamp-img {
background:url('images/time_stamp_list_icon_play.png');
}
.time-stamp-img:hover {
background:url('images/time_stamp_list_icon_hover.png');
}
html:
<div class="time-stamp-img"></div>
I'd use https://api.jquery./data/ and just set a data point on the element of the original source, and then just retrieve it on mouse out.
Building on Dylan Watt's suggestion I'd use .data()
to avoid a global variable.
So something like this:
$("span").mouseenter(function () {
var currentImage = $('img', this).attr("src");
$('img', this).data("orig", currentImage)
.attr("src", "http://placehold.it/350x150&text=hover");
}).mouseleave(function () {
var original = $('img', this).data("orig");
$('img', this).attr("src", original);
});
And here's the fiddle that's from that you can adapt for your use:
http://jsfiddle/djfe7rum/1/
I would suggest using mouseenter, mouseleave, as such:
var currentImage;
$("#parent span").mouseenter(function(){
currentImage = $('img', this ).attr("src");
$('img', this ).attr("src","images/yellowBar.png");
}).mouseleave(function(){
$('img', this ).attr("src", currentImage);
});
If this doesn't work, please provide your HTML code.