Matthew Cumbo Matthew Cumbo - 3 months ago 13
jQuery Question

JQuery opacity not animating

I created the following function to have 4 images (all in separate divs to have links with them) fade in and out as a sort of gallery. It works, but when it's time for the fourth image to fade out and the first to show up instead, the fading is not working, it just changes z-index and the first is shown. Anyone have an idea why this is happening?



$(function() {
setInterval("Fader()", 5000);
});

function Fader() {
var $active = $('#slider DIV.active');
var $next;
if ($active.length == 0) $active = ('#slider DIV:last');

if ($active.next().length == 0) {
$next = $('#slider DIV:first');
} else {
$next = $active.next()
}

$active.addClass('last-active');

$next.css({
opacity: 0.0
})
.addClass('active')
.animate({
opacity: 1.0
}, 1000, function() {
$active.removeClass('active last-active');
});
}

#fp1img,#fp2img,#fp3img,#fp4img {
z-index: 8;
}
#fp1img.last-active,#fp2img.last-active,#fp3img.last-active,#fp4img.last-active {
z-index: 9;
}
#fp1img.active,#fp2img.active,#fp3img.active,#fp4img.active {
z-index: 10;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id='slider'>
<div class="fpImgCrop active" id="fp1img">
<a id='fp1link' href="">1</a>
</div>
<div class="fpImgCrop" id="fp2img">
<a id='fp2link' href="">2</a>
</div>
<div class="fpImgCrop" id="fp3img">
<a id='fp3link' href="">3</a>
</div>
<div class="fpImgCrop" id="fp4img">
<a id='fp4link' href="">4</a>
</div>
</div>




Answer

Fixed this with a simple solution. Where the classes active and last-active are removed, I only removed last-active. I removed active before the animation takes place.

$active.addClass('last-active'); 
$active.removeClass('active'); 
$next.css({opacity:0.0}) 
.addClass('active') 
.animate({opacity:1.0},1000,function(){ 
$active.removeClass(' last-active'); });
Comments