0

Possible Duplicate:
jQuery fade to new image

I have the following code to swap (preloaded) images on hover:

$(document).ready(function() { 
$(".pf-item img").hover(
      function(){this.src = this.src.replace(".jpg","-h.jpg");},
      function(){this.src = this.src.replace("-h.jpg",".jpg");
 });
 var imgSwap = [];
 $(".img-swap").each(function(){
    imgUrl = this.src.replace(".jpg","-h.jpg");
    imgSwap.push(imgUrl);
});
$(imgSwap).preload();
});
$.fn.preload = function() {
this.each(function(){
    $('<img/>')[0].src = this;
});
}

It works really well, however I'd like to be able to fade between the images .jpg and -h.jpg.

Does anyone know how to do this/have a better way of approaching the issue? I have attempted lots of different fadeIn() approaches, but all seem to either not work, or work for a few hovers, then replace a blank image.

Community
  • 1
  • 1
Jamie
  • 332
  • 1
  • 3
  • 14
  • 1
    You have to position one image above the other (using CSS `position: absolute;`), and `fadeOut()` the top one. There'll be a jQuery plugin to do it somewhere. – Matt Jul 17 '12 at 10:02
  • http://stackoverflow.com/questions/11369182/how-to-replace-elements-attr-href-with-each-strip-url – Barlas Apaydin Jul 17 '12 at 10:06
  • possible duplicate of [jQuery fade to new image](http://stackoverflow.com/questions/1977557/jquery-fade-to-new-image) or [Smooth image fade out, change src, and fade in with jquery](http://stackoverflow.com/questions/9959926/smooth-image-fade-out-change-src-and-fade-in-with-jquery) - see also [here](http://stackoverflow.com/search?q=jquery+fade+images&submit=search) – Bergi Jul 17 '12 at 10:17

1 Answers1

2

Id suggest using a mouseover/mouseout approach.

Id have my HTML set out like this.

<div class="imageWrap">
    <img class="shown" src="image-1.jpg" width="300" height="300" />
    <img class="hidden" src="image-2.jpg" width="300" height="300" />
</div>

Then using jQuery you can swap between them like so

$(".imageWrap").mouseover(function() {
    $(this).children(".shown").fadeOut("fast");
    $(this).children(".hidden").fadeIn("fast");
});

$(".imageWrap").mouseout(function() {
    $(this).children(".shown").fadeIn("fast");
    $(this).children(".hidden").fadeOut("fast");
});

Dont forget your css

.imageWrap {width:300px; height:300px;}
.imageWrap > img {position:absolute;}
.imageWrap > .hidden {display:none;}
Undefined
  • 11,234
  • 5
  • 37
  • 62