Background image transition using jQuery

I made a little jQuery code that changes the background image of a field.

HTML

<div class="content-wrapper" id="box">
    <div class="content">
        CONTENT
    </div>
</div>

JQuery

     slide=Math.floor((Math.random() * 6) + 1); slide=(slide==0?1:slide);
        $("#box").attr("style", "background-image:url(images/slider/"+(slide)+".jpg);");
        setInterval(function() {
            $("#box").attr("style", "background-image:url(images/slider/"+(slide)+".jpg);");
            slide++; if(slide>6) slide=1;
        }, 6000
);

CSS

.content-wrapper{
    display:table;
    width:100%;
    color:black;
    text-align:center;
    margin:0 0 0 0 !important;
    padding:0px !important;
    height:600px;
}
.content-wrapper > .content{
    width:100%;
    display: table-cell;
    vertical-align:middle;
    text-align:center;
    font-size:36px;
    font-weight:bold;
}
#box {
    background-repeat: no-repeat;
    background-position:center top;
    background-attachment:fixed;
    background-size:cover;
}
#box > .content{
    background:rgba(0,0,0,0.5);
    color:#FFF;
}

Demo

My idea is when the page is loaded every time random images are displayed and a slide is launched that changes the image every 6 seconds. This all works well, but I don’t know how to make a good transition. fadeIn () or fadeOut () is out of the question because I have fixed text content on the images. I do not want to use too large libraries for the background slider, so I'm interested in the simplest solution. Thank you very much.

+4
source share
1 answer

Fiddle: Demo:

    $(document).ready(function () {
    var delay = 3000,
        fade = 1000;
    var banners = $('.banner');
    var len = banners.length;
    var i = 0;
    setTimeout(cycle, delay);

    function cycle() {
        $(banners[i % len]).hide("slide", function(){
             $(banners[++i % len]).show("slide", {
                direction: "left"
            });
            setTimeout(cycle, delay);
        });
    }
});

: Fiddle

    $(document).ready(function() {

    var delay = 3000, fade = 1000;
    var banners = $('.banner');
    var len = banners.length;
    var i = 0;

    setTimeout(cycle, delay);

    function cycle() {
        $(banners[i%len]).slideUp(fade, function() {
            $(banners[++i%len]).slideDown(fade, function() {
                setTimeout(cycle, delay);   
            });
        });
    }

});

, .

+3

All Articles