The Riot
The Riot

Reputation: 41

Change the background of a div with jquery easing the process

I was looking for a way to change the background of a div using jQuery and I found this question:

change background image jquery

I made it and it's working. But, there's a way to ease the process? Like an fade-in/out?

Sorry for my english. And thank you for your time.

UPDATE:

.branding{
     min-height:530px;
     background-image:url(../images/brandings-0.jpg);
     background-repeat:no-repeat; 
     background-position:center;
}

var newBg = [
    'site/assets/images/brandings-1.jpg',
    'site/assets/images/brandings-2.jpg',
    'site/assets/images/brandings-3.jpg'];

    var i = 0;

var rotateBg = setInterval(function(){
    i++;
    if(i > 2)
        i=0;

    $('.branding').css({backgroundImage : 'url(' + newBg[i] + ')'});
}, 5000); 

<div class="branding"></div>

Upvotes: 2

Views: 155

Answers (2)

Ryan
Ryan

Reputation: 291

Try the following fiddle I created for you.

http://jsfiddle.net/ujyjcfea/1/

var i = 0;

var newBg = [
    'http://lorempixel.com/output/animals-q-c-640-480-2.jpg',
    'http://lorempixel.com/output/animals-q-c-640-480-1.jpg',
    'http://lorempixel.com/output/animals-q-c-640-480-4.jpg'];

var image = $('.branding');


image.css('background-image', 'url(http://lorempixel.com/output/animals-q-c-640-480-2.jpg)');


setInterval(function () {

    image.fadeOut(1000, function () {

        image.css('background-image', 'url(' + newBg[i++] + ')');

        image.fadeIn(1000);

    });

    if (i == newBg.length)

    i = 0;
}, 5000);

http://www.programming-free.com/2013/12/change-background-image-jquery.html

Upvotes: 1

Vitorino fernandes
Vitorino fernandes

Reputation: 15951

demo - http://jsfiddle.net/victor_007/RyGKV/643/

var i = 0;
var images = ['http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg',               'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-2.jpg', 'http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg'];
var image = $('#slideit');

image.css('background-image', 'url(http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg)');  //Initial Background image setup

setInterval(function () {
    image.fadeOut(1000, function () {
        image.css('background-image', 'url(' + images[i++] + ')');
        image.fadeIn(1000);
    });
    if (i == images.length) i = 0;
}, 5000);

Upvotes: 1

Related Questions