Reputation: 11
I'm trying to grasp how I might use jQuery to change the image source to a second image using html data attributes on hover, with a fadeOut/fadeIn effect.
It would look like this:
Here's what I have so far in the DOM:
<img class="myimageclass" src="http://www.example.com/path-to/picture.jpg" data-alt-src="http://www.example.com/path-to/picture-alt.jpg" alt="my picture">
Any suggestions on the best way to implement this?
EDIT: Here's the JavaScript I have so far, and I've been able to get the image to swap, but where I get stuck is firing the fadeIn/fadeOut methods :
$( document ).ready(function() {
var sourceSwap = function () {
var $this = $(this);
var newSource = $this.data('alt-src');
$this.data('alt-src', $this.attr('src'));
$this.attr('src', newSource);
}
$(function () {
$('img.myimgclass').hover(sourceSwap, sourceSwap);
});
});
Upvotes: 0
Views: 724
Reputation: 36703
$(".myimageclass").hover(function () {
$(this).fadeOut(2000);
setTimeout(function () {
var temp = this.getAttribute("data-src");
this.setAttribute("data-src", this.src);
this.src = temp;
$(this).fadeIn(2000);
}, 2000);
},
function () {
$(this).fadeOut(2000);
setTimeout(function () {
var temp = this.getAttribute("data-src");
this.setAttribute("data-src", this.src);
this.src = temp;
$(this).fadeIn(2000);
}, 2000);
});
Upvotes: 1