jaworrom
jaworrom

Reputation: 11

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://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

Answers (1)

void
void

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

Related Questions