Search code examples
jquerysettimeoutfadeinfadeout

Using fadeIn fadeOut on setTimeout?


Can I use a fadeIn or fadeOut on a setTimeout? I have 3 background images in an array and I want to fade each one in slowly.

This is my code that works fine, I would just like the transition to be slow rather than super quick as it is now.

$(function () {
var nextImage = $('.main-background');
var backgrounds = [
  'url(<?= $image_url ?>/big-main-background-1.jpg)', 
  'url(<?= $image_url ?>/big-main-background-2.jpg)', 
  'url(<?= $image_url ?>/big-main-background-3.jpg)'];

var current = 0;

function nextBackground() {
    nextImage.css(
        'background',
    backgrounds[current = ++current % backgrounds.length]);

    setTimeout(nextBackground, 4000);
}
setTimeout(nextBackground, 4000);
nextImage.css('background', backgrounds[0]);
});

Solution

  • Please check this fiddle: https://jsfiddle.net/3xdzxpmh/1/

    Here's a different approach, you can feel free to ask if you have any question.

    Just replace the style or the content with the background of yours.

    If you want to apply this to your container, insert the following structure into your main container and max out it's width and height.

    Here's the structure:

    <div class="container">
        <div style="background:red"></div>
        <div style="background:yellow"></div>
        <div style="background:blue"></div>
    </div>
    

    Here's the JS I've modified from your code:

    var current = 0;
    $(function(){
        var l = $(".container div").length;
        change();
        function change() {
            current = ++current % l;
            $(".container div").removeClass("show");
            $(".container div:nth-child("+(current+1)+")").addClass("show");
            setTimeout(change,2000);
        }
    });
    

    And here's the CSS:

    .container {
        position:relative;
    }
    
    .container > div {
        width:200px;
        height:200px;
        top:0;
        left:0;
        position:absolute;
        opacity:0;
        transition:1s all ease;
    }
    
    .container > div.show {
        opacity:1;
    }
    

    Basically, the CSS class .show states that the element must be opaque. The .container div sets a style of transparent and has a transition. When .show is toggled, 2 <div> fade together, creating the effect.