lundi 23 février 2015

How might I add a fade in/fade out on hover using HTML5 data attributes?

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:



  1. On hover, first image fades out.

  2. Second image from data-alt-src is faded in.

  3. On mouse out, it fades back to first image from original src.


Here's what I have so far in the DOM:



<img class="myimageclass" src="http://ift.tt/1w38WT1" data-alt-src="http://ift.tt/1w38UdS" 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);
});
});

Aucun commentaire:

Enregistrer un commentaire