2
votes

Using alternate data attributes for image rollovers, as outlined here: Best way to do image rollovers? and I can't figure out how to add a fade into attr swap.

Basically, on hover the img src changes, and that works perfectly. But is there a way to make it fade in/out?

$(function(){
  $('img.rollover').hover(function(){
    var e = $(this);
    e.data('originalSrc', e.attr('src'));
    e.attr('src', e.attr('data-rollover'));
}, function(){
    var e = $(this);
    e.attr('src', e.data('originalSrc'));
}); /* a preloader could easily go here too */ 
});

Jsfiddle here: http://jsfiddle.net/dtPRM/1/

Seems like a case for fadeToggle, but I've tried it in a couple places to no avail.

Also confused about the comma separated function on line six, though it seems to denote Not hovering.

Thanks

2
the comma separated function is the "hoverout-function" that gets executed when the mouse leaves the elementjohn Smith

2 Answers

1
votes

i just set the elements opacity to 0, then change img-src and then animate to opacity:1

$(function(){
$('img.rollover').hover(function(){
    var e = $(this);
    e.data('originalSrc', e.attr('src'));
    e.css('opacity',0);
    e.attr('src', e.attr('data-rollover'));
    e.animate({"opacity":1},400);
}, function(){
    var e = $(this);
    e.css('opacity',0);
    e.attr('src', e.data('originalSrc'));
    e.animate({"opacity":1},400);
}); /* a preloader could easily go here too */
});

http://jsfiddle.net/dtPRM/51/

0
votes

Here's a jsfiddle

In order to get a fade-out when mousing over, I animated a fadeout which had a callback that changed the source and then faded back in.

e.animate({opacity: 0},1000, function() {
    e.data('originalSrc', e.attr('src'));
    e.attr('src', e.attr('data-rollover'));
    e.animate({opacity: 1},1000);
});