nick nick - 1 year ago 91
jQuery Question

jQuery swap image on hover, then replace it with original on hover off

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


$('img', this ).attr("src",currentImage);


Answer Source

Define 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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download