2

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>
Community
  • 1
  • 1
The Riot
  • 41
  • 3
  • 10

2 Answers2

1

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);
Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39
1

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

Community
  • 1
  • 1
Ryan
  • 295
  • 2
  • 8
  • If I put some content in the body, will it fade the div and the content or only the background? – The Riot Oct 20 '14 at 18:42
  • Yes (if the text is part of the .branding element), however if yo uput it in a container and add an additional element for the text, it will transition behind the text. http://jsfiddle.net/ujyjcfea/11/ – Ryan Oct 20 '14 at 18:49