Reputation: 1931
Ok I have to two images on a page that I want to cross fade between on mouse over and on mouse out i want it to reverse so the image looks as if it reverting back to its original state.
Right now I it have working by fading out the first image then fading the replacement back in as below how do I make this cross fade as above?
$("#img-swap1 img").mouseover(function() {
$("#img-swap1 img").fadeOut(350, function() {
$(this).attr("src", "images/dentalwise-hover.jpg","images/dentalwise.jpg");
$(this).fadeIn(350);
});
}).mouseout(function(){
$("#img-swap1 img").fadeOut(350, function() {
$(this).attr("src", "images/dentalwise.jpg","images/dentalwise.jpg");
$(this).fadeIn(350);
});
});
the html:
<div id="main-content">
<div class="featured">
<div class="featured-heading">
<h3>Recent Works</h3>
<p class="sub-heading">Check out my latest work</p>
</div>
<p class="featured-para">
Elementum sed pid nunc, placerat quis parturient,
sit nascetur? Mid placerat vel, cum scelerisque diam.
placerat quis parturient dolorElementum sed pid
placerat quis parturient.
</p>
</div>
<div id="latest-w" class="pleft">
<div class="latest-img">
<a id="img-swap1" class="img-swap" href="#">
<img src="images/dentalwise.jpg" width="191" height="129" />
</a>
</div>
</div>
<div id="latest-w" class="pleft">
<div class="latest-img">
<a id="img-swap2" class="img-swap" href="#">
<img class="img-swap" src="images/wyevallay.jpg" width="191" height="129" />
</a>
</div>
</div>
<div id="latest-w" class="pleft">
<div class="latest-img">
<a id="img-swap3" class="img-swap" href="#">
<img src="images/easycms.jpg" width="191" height="129" />
</a>
</div>
</div>
</div>
Upvotes: 1
Views: 336
Reputation: 30099
If your images all follow the same pattern, i.e. name.jpg
-> name-hover.jpg
, you can automate the whole process:
$(function() {
// Create your hover images:
$('.img-swap img').each(function() {
// Construct your hover img src:
var src = $(this).attr('src').replace(/\.jpg/, '-hover.jpg');
// Clone the img, give it the new src,
// place the clone after the original,
// and position it underneath
var offset = -$(this).outerWidth();
$(this).clone()
.attr('src', src)
.css({position: 'relative', left: offset+'px', zIndex: -1})
.insertAfter($(this));
});
// Create mouseover to "cross-fade":
$('.img-swap').on('mouseover', 'img', function() {
// Keep it barely visible, so it doesn't re-flow the DOM
$(this).stop().fadeTo(350, .01);
}).on('mouseleave', 'img', function() {
$(this).stop().fadeTo(350, 1);
});
});
Here is a jFiddle example: http://jsfiddle.net/jtbowden/xqUQ6/3/
Upvotes: 0
Reputation: 15652
Well you should have two separate images. Place one behind the other. Then you can fade the one on top out and it will have the effect of "cross-fading". If you're only changing the src
of the image, there is no way to have it cross-fade.
Upvotes: 1