Search code examples
javascripthtmlcsstransitiontimed

How to call this timed transitereion in javascript


I am trying to get 6 divs to fade in and then out for a period of 5 seconds. Div1 will show first onClick and then last for 5 seconds, and then it will fade out while the next on in order pops up and then fades out, and so on. I have been playing with this JavaScript - but I am having some trouble - 1) calling it when a button is clicked and 2) how do I write a code that allows for a 1 second overlap?

Any help? Here is my JavaScript:

$(function () {

    var counter = 0,
        divs = $('#tutorial1, #tutorial2, #tutorial3, #tutorial4, #tutorial5, #tutorial6');

    function showDiv () {
        divs.hide() // hide all divs
            .filter(function (index) { return index == counter % 3; }) // figure out correct div to show
            .show('fast'); // and show it

        counter++;
    }; // function to loop through divs and show correct div

    showDiv(); // show first div    

    setInterval(function () {
        showDiv(); // show next div
    }, 5 * 1000); // do this every 5 seconds    

});

Solution

  • http://jsfiddle.net/NpNXr/1/

    HTML (I added the class fader to indicate that these are part of the animation)

    <div class="fader" id="tutorial1">One</div>
    <div class="fader" id="tutorial2">Two</div>
    <div class="fader" id="tutorial3">Three</div>
    <div class="fader" id="tutorial4">Four</div>
    <div class="fader" id="tutorial5">Five</div>
    <div class="fader" id="tutorial6">Six</div>
    
    <input type="button" value="Start" id="start"/>
    

    JS

    function fadeLoop() {
    
        var counter = 0,
            divs = $('.fader').hide(), // Selecting fader divs instead of each by name.
            dur = 500;
    
        function showDiv() {
            divs.fadeOut(dur) // hide all divs
                .filter(function(index) {
                    return index == counter % divs.length;
                }) // figure out correct div to show
                .delay(dur) // delay until fadeout is finished
                .fadeIn(dur); // and show it
            counter++;
        }; // function to loop through divs and show correct div
        showDiv(); // show first div    
        return setInterval(function() {  // return interval so we can stop the loop
            showDiv(); // show next div
        }, 5 * 1000); // do this every 5 seconds    
    };
    
    $(function() {
        var interval;
    
        $("#start").click(function() {
            if (interval == undefined){
                interval = fadeLoop();
                $(this).val("Stop");
            }
            else{
                clearInterval(interval);
                $(this).val("Start");
                interval = undefined;
            }
        });
    });​