How to evenly time fading transitions?

59 views Asked by At

so I'm trying to create a simple slide show from scratch, and so far I was able to get full screen images to fade out and fade in infinetly, but for some odd reason using setInterval(function(){fade(var)}, 3500);didn't work, maybe someone can explain why the first and last images took way longer than 3,5 seconds to fade. Meanwhile, I was trying to solve that problem by implementing a callback function in the fade(). My example has four images, and they start fading out until it reaches image one, then don't fade out image one and start fading back in image two until image 4, and do this forever, here is my recent attempt to implement a callback function:

var i = 4;

$(document).ready(function(){
            fade(i, fade);
});

var fadeIN = false;
function fade(objectID, callbackfn){
    var fadeTime = 3500;
    if(!fadeIN){
        $("#slide-"+objectID).fadeOut(fadeTime);
        i--;
        if(i === 1) {
            fadeIN = true;
        }
    }
    else{
        i++;
        $("#slide-"+objectID).fadeIn(fadeTime);
        if(i === 4){
            fadeIN = false;
        }
    }
    if(arguments[1]){
        callbackfn(i);
    }
}

But that is not working, it fades out image 4, image 3 and stops on image 2. Maybe there is a way to evenly time the fading transitions using the setIntervel(), if so can someone tell me how? Appreciate any help.

Here is a JSFiddle to the code: http://jsfiddle.net/8kgc0chq/ it is not working tho.

2

There are 2 answers

7
Stefan Dimov On BEST ANSWER

Here is the doc for .fadeOut()

There is an optional argument complete:

A function to call once the animation is complete.

Put the next animation in there, they too take a complete (callback) function.

$("#id").fadeOut(fadeTime, function() {
    // code to execute after animation complete 
});
4
Muhammad Umer On

You need to do it properly with javascript. Easy way fails after last element.

So here is my solution. Can it be improved further, I think yes.. But it does work now. And is future proof to some extent.

I cleaned up css and changed html structure a little.

Demo: http://jsfiddle.net/8kgc0chq/3/

$(document).ready(function () {
    $(window).resize(function () {
        realTimeHeight();
    });
    realTimeHeight();
    startSlides();
});


function startSlides() {
    var fadeTime = 1000,
        delay = 1300,
        i = 0,
        slides = $("#hero-slider > .slide"),
        len = slides.length;

    slides.hide();

    var pF = $('<div class="slide">'), pB = pF.clone();
    pF.attr('id', slides.eq(i).attr('id'));
    $('#hero-slider').prepend(pF).prepend(pB);
    setInterval(fadeThisIn, fadeTime + delay);

    function fadeThisIn() {
        pB.attr('id', pF.attr('id'));
        i = ++i % len;
        pF.hide().attr('id', slides.eq(i).attr('id')).fadeIn(fadeTime);
    }
}

function realTimeHeight() {
    var altura = $(window).height();
    $("#hero-slider").css("height", altura);
}