Reputation: 151
I'm trying to fade out an image and fade in another which has display
set to none
. I can do it using fadeToggle
but I would like to add a delay to avoid having the second image display before the first one finishes fading out.
Found this question here that kind of gives me the answer: jQuery fadeToggle one after the other
This answer uses different classes but I would like to use the class of the parent element to the images to fade out the first child and fade in the second child. Then once it's clicked again reverse all.
I have the first part working which fades out image 1 and then fades in image 2 after a delay. But when I click again, image 2 fades out and fades back in.
Here my html:
<div class="item">
<div class="target">
<div class="visOn"><img src="http://placehold.it/300x300" alt=""></div>
<div class="visOff"><img src="http://placehold.it/200x200" alt=""></div>
</div>
</div>
Here's the CSS:
.visOff{
display:none;
Here's the JS:
$('.target').click(function(){
var icon1 = $(this).children();
var icon2 = $(this).children().eq(1);
if (icon1.is(':visible')){
icon1.fadeOut('slow');
icon2.delay(500).fadeIn('slow');
}
else if (icon2.is(':visible')){
icon2.fadeOut('slow');
icon1.delay(500).fadeIn('slow');
}
});
Here's a JSFiddle - https://jsfiddle.net/asantoni/ex30v3rh/
Upvotes: 1
Views: 1186
Reputation: 169
You can also try a different approach,
I've updated the JSFiddle, this does not toggle, but works with classes, the benefit is that this also gives you more control on the behavior of the elements.
var switchFade = function(){
e_on = $('.visOn');
e_off = $('.visOff');
$(e_on).animate({'opacity':0},'slow',function(){
$(e_on).removeClass('visOn').addClass('visOff');
$(e_off).addClass('visOn').removeClass('visOff');
$(e_off).css({'opacity':0});
$(e_off).animate({'opacity':1},'slow');
});
};
$('.target').click(function(){
switchFade();
});
https://jsfiddle.net/ex30v3rh/5/
Upvotes: 0
Reputation: 22158
You need to solve with a simple CSS
https://jsfiddle.net/ex30v3rh/1/
.target {
position: relative;
}
.target > div {
position: absolute;
}
Upvotes: 3