15

Hey i want to fade in a new background image let´s say every 60 seconds. I´ve set the background image like this:

body {background-image: url(background.jpg);}

Now i want to change it, so after 60seconds it changes to background2.jpg, then after 60 seconds to background3.jpg and so on..

I´ve found a lot of stuff without changing it in the body but just as an image... any quick solutions?

Thank you!

Marc Ster
  • 2,276
  • 6
  • 33
  • 63
  • Did you try using a JS slider for this? This is doable using css3 transform and transition delays but it wont be as reliable as a jquery slider, Basically you can have a jquery slider with the images inside position it fixed on the body tag then add `z-index: -1` on the slider container and it should stay behind the page content, You can set the height and width of the slider container by using jquery windowHeight and windowWidth. – youssef Nov 28 '13 at 00:58

7 Answers7

20

Re-UPDATE of the UPDATE:

Even NEWER Fiddle (without arguments.callee)

Changes:


BIG UPDATE


Took the meat of this code from this previous answer and added some bling (using my site background stash lol)

original fiddle :)

NEW Super Fiddle

Javascript:

$(document).ready(function () {
    var img_array = [1, 2, 3, 4, 5],
        newIndex = 0,
        index = 0,
        interval = 5000;
    (function changeBg() {

        //  --------------------------
        //  For random image rotation:
        //  --------------------------

            //  newIndex = Math.floor(Math.random() * 10) % img_array.length;
            //  index = (newIndex === index) ? newIndex -1 : newIndex;

        //  ------------------------------
        //  For sequential image rotation:
        //  ------------------------------

            index = (index + 1) % img_array.length;

        $('body').css('backgroundImage', function () {
            $('#fullPage').animate({
                backgroundColor: 'transparent'
            }, 1000, function () {
                setTimeout(function () {
                    $('#fullPage').animate({
                        backgroundColor: 'rgb(255,255,255)'
                    }, 1000);
                }, 3000);
            });
            return 'url(http://www.fleeceitout.com/images/field.' + img_array[index] + '.jpg)';
        });
        setTimeout(changeBg, interval);
    })();
});

CSS:

body {
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
    position: relative;
    background-image: url(http://www.fleeceitout.com/images/field.2.jpg);
    background-size: cover;
    background-repeat: no-repeat;
    background-position: 0 0;
    background-attachment: fixed;
}
#fullPage {
    position: absolute;
    min-width: 100%;
    min-height: 100%;
    top: 0;
    left: 0;
    background-color: rgb(255, 255, 255);
}
Community
  • 1
  • 1
Deryck
  • 7,608
  • 2
  • 24
  • 43
  • thank you, looks good! Is there a way to use the jquery fade effect instead of using css in this code? – Marc Ster Nov 28 '13 at 02:03
  • no unfortunately you can't transition the `background-image` property without CSS that I'm able to find (jQuery UI states this explicitly in the first couple paragraphs here: http://api.jqueryui.com/toggleClass/ - "Not all styles can be animated. For example, there is no way to animate a background image. Any styles that cannot be animated will be changed at the end of the animation." ) I started to make a new edit to my fiddle with an attempt at this but this is as far as I got unfortunately. http://jsfiddle.net/VX2Zw/2/ – Deryck Nov 28 '13 at 02:43
  • thank you for your time and help! I think i know enough to go on now – Marc Ster Nov 28 '13 at 02:54
  • 1
    WAIT I GOT IT LOL WOW this is pretty roundabout but it can even be supported by – Deryck Nov 28 '13 at 03:05
  • 1
    nice job! :D didn´t expect something like this but it works ty – Marc Ster Nov 28 '13 at 04:02
  • Great job Deryck. I already upvoted your previous answer, wish I could add +10 to that. – cssyphus Nov 28 '13 at 16:27
  • hahaha oddly enough I did a similar question a little while after and now that I just revisited that fiddle I found some ways to improve it. Adjusted to be cute as a button: http://jsfiddle.net/VX2Zw/4/ – Deryck Nov 28 '13 at 16:32
  • Hello all. Is there any way around not using arguments.callee? – Greg K. Feb 08 '14 at 00:42
  • I have re-updated the code to oblige and also fixed an error that was previously occurring that I was unaware of in the CSS. This is a bit cleaner: http://jsfiddle.net/M2LmH/ – Deryck Feb 08 '14 at 01:27
  • 1
    Nah just took my server down for a minute lol. Thanks for the heads-up @DenisV - well I was gonna go change it to work but now can't find the images damn – Deryck Jul 23 '14 at 23:19
  • essa porra não funciona. – user3632930 Sep 03 '14 at 13:01
  • @user3632930 porque se eliminaron las fotos. lo siento – Deryck Sep 03 '14 at 22:34
  • @gibberish funny cuz the original fiddle for this got so popular I had to put a 301 handler on my server so it wouldn't look for the original pics anymore. Now I make it point to placekitten.com instead. lol thanks for the mirror + edit :) – Deryck Feb 20 '15 at 11:58
  • Your random rotate is cool, but has a bug: `index = (newIndex === index) ? newIndex -1 : newIndex`. Your scheme for case where same image is picked again is to decrement by one which sometimes results in `index === -1` and `url === undefined`, but easy to fix of course. thanks – nothingisnecessary Nov 03 '15 at 06:21
13

You can use the setInterval method and switch between classes defined in your CSS which have different background-images:

setInterval(function() {
    var $body = $('body');
    if($body.hasClass('background1'))
    {
        $body.removeClass('background1');
        $body.addClass('background2');
    }
    else {        
        $body.removeClass('background2');
        $body.addClass('background1');
    }
}, 1000);

Fiddle

This example uses an interval of 1000 which is one second. You can change this value for whatever period of time you're looking for.

UPDATE

Noticed your question asked for a fade so I added a CSS3 property on body:

body
{
    transition: background 0.5s linear;
}

The fiddle has been updated.

Dan-Nolan
  • 6,594
  • 4
  • 27
  • 32
9

Building on the answer from Dan-Nolan (formerly user506980), you can also assign the backgrounds to an array and then call each background from the array with a counter

jsFiddle Demo

Further, you can assign the setInterval function to a variable, and then use that variable later to stop the repeats.

$(document).ready(function() {
    var cnt=0, bg;
    var $body = $('body');
    var arr = ['bg1.jpg','bg2.jpg','bg3.jpg','bg4.jpg','bg5.jpg','bg6.jpg'];
    
    var bgrotater = setInterval(function() {
        if (cnt==5) cnt=0;
        bg = 'url("' + arr[cnt] + '")';
        cnt++;
        $body.css('background-image', bg);
    }, 1000);
    
    //To stop the backgrounds from rotating. Note the critical step above
    //of assigning the setInterval function to a variable, in order to
    //use it again (below) to stop the repeating function
    $('#some_button_id').click(function() {
        clearInterval(bgrotater);
    });

}); //END document.ready
halfer
  • 19,824
  • 17
  • 99
  • 186
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • No need for thanks - only giving credit where credit was deserved. Well done on your answer. – cssyphus Nov 28 '13 at 02:20
  • Thank you! Like i already asked above, is it possible to implement the jquery fade effect instead of using css? – Marc Ster Nov 28 '13 at 02:23
  • Check out this answer: http://stackoverflow.com/questions/977090/fading-in-a-background-image and http://stackoverflow.com/questions/12227901/fade-in-background-image-with-jquery – cssyphus Nov 28 '13 at 02:34
  • Thank you both! Maybe i should really use a jsslider or an image as background. – Marc Ster Nov 28 '13 at 02:54
  • can you please add fade out and fade in while image changing – Sunil Acharya Feb 18 '15 at 14:28
  • @skgacharya See new jsFiddle Demo added to my answer. The fadeIn fadeOut is added by the css mod: `transition: 2.5s`. Note that I changed the jQuery `.css()` method to `.css({})` (use object) in order to specify multiple css changes that must happen together. – cssyphus Feb 18 '15 at 17:07
  • @MarcSter Sorry for not answering your 13-11-28 question sooner. This response, then, is more for future readers, since you probably already found the answer. For the newcomers, then, we cannot use jQuery's `.fadeIn()` method for an image applied as the background to the body element, because `fadeIn()` fades the visibility of the element itself -- and a web page with a hidden body element is... um... not optimal. Thus, css to the rescue. – cssyphus Feb 18 '15 at 17:44
3

https://github.com/srobbin/jquery-backstretch Backstretch is a simple jQuery plugin that allows you to add a dynamically-resized, slideshow-capable background image to any page or element. The image will stretch to fit the page/element, and will automatically resize as the window/element size changes.

Kenrick
  • 31
  • 3
0
jQuery(document).ready(function() {
var cnt=0, bg;
var $body = jQuery('body');
var arr = ['secondbg.jpg','sartulebis-archeva2.png'];

animate = function(){

}
var bgrotater = setInterval(function() {
    if (cnt==2) cnt=0;
    bg = 'url("http://yalcingroup.ge/test/wp-content/uploads/2015/08/' + arr[cnt] + '")';
    cnt++;
    jQuery('#background_cycler').animate({opacity:1}, 2000, function(){
        $body.css('background-image', bg);
    });


    jQuery('#background_cycler').animate({opacity:0}, 2000);
},10000);

});

George
  • 1
  • 1
0

Each 12 seconds an image is changed in presentacion container; it can be body tag

HTML

<div class="presentacion">
  <div class="mask"></div>
</div>

JS

delay(11000) + setTimeout(1000) = 12 sec transition duration = 300 + 300 = 600 msec

var imgArray = ['image-1', 'image-2', 'image-3'], index = 0;

(function changeBG(){
  // mask element only for transition
  $('.mask').delay(11000).animate({opacity:1}, 300, function(){
    index = (index + 1) % img_array.length;
    // in presentacion element change bg images
    $('.presentacion').css("background-image", "url('images/bg-"+imgArray[index]+".jpg')");
  }).animate({opacity: 0}, 300);
  setTimeout(changeBG, 1000);
})();

CSS

.presentacion {
  background-attachment: fixed;
  background-color: rgba(0, 0, 0, 0.5);
  background-image: url("images/image-1.jpg");
  background-position: center center;
  background-repeat: no-repeat;
  -webkit-background-size: cover;
  background-size: cover;
  position: relative;
  width: 100%;
  z-index: 0;
  opacity: 1;
}
.mask {
  background-color: rgba(0,0,0,0);
  bottom: 0;
  left: 0;
  opacity: 0;
  position: absolute;
  right: 0;
  top: 0;
  height: 100%;
  z-index: 10;
}
0

Building on Deryck's answer...

If jQuery Color does not function properly (which it sometimes does), you can use fadeIn() and fadeOut() instead:

 $(document).ready(function () {
    var img_array = [1, 2, 3, 4, 5],
        newIndex = 0,
        index = 0,
        interval = 5000;
    (function changeBg() {

        //  --------------------------
        //  For random image rotation:
        //  --------------------------

            //  newIndex = Math.floor(Math.random() * 10) % img_array.length;
            //  index = (newIndex === index) ? newIndex -1 : newIndex;

        //  ------------------------------
        //  For sequential image rotation:
        //  ------------------------------

            index = (index + 1) % img_array.length;

        $('body').css('backgroundImage', function () {
            $('#fullPage').fadeOut(1000, function () {
                setTimeout(function () {
                    $('#fullPage').fadeIn(1000);
                }, 3000);
            });
            return 'url(http://www.fleeceitout.com/images/field.' + img_array[index] + '.jpg)';
        });
        setTimeout(changeBg, interval);
    })();
});
ckhatton
  • 1,359
  • 1
  • 14
  • 43