szarin2
szarin2

Reputation: 23

Changing background image - javascript

I would like to change a background image with JavaScript.

JS:

<head>
<script type="text/javascript">
    // Ta funkcja odpowiedzialna jest odpowiedzialna za zmiane obrazow w tle
  $(window).load(function(){
     var i = 0;
     var images = ['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg','images/5.jpg'];
     var image = $('#slideit');
     image.css('background-image', 'url(images/1.jpg)');
     image.css('background-size', 'cover');
     setInterval(function(){
          image.css('background-image', 'url(' + images [i++] +')');
          // image.fadeOut(1500, function (){
          //     image.fadeIn(1000);
          // })
          if(i == images.length) i = 0;
     }, 6000);
 });
</script>
</head>

HTML:

<body id="slideit" style="width:100%;height:100%;">

The problem is in making the images change smoothly. The commented out code makes everything in the website fade in and fade out except the background. Why is this happening? This code works but does not change the image smoothly. How can I fade the images in and out?

Upvotes: 0

Views: 1768

Answers (2)

guest271314
guest271314

Reputation: 1

Try

$(function() {
  $.fx.interval = 3000;
  (function cycleBgImage(elem, bgimg) {
    elem.css("backgroundImage", bgimg).delay(3000, "fx")
      .fadeTo(3000, 1, "linear", function() {
        $(this).fadeTo(3000, 0, "linear", function() {
          var img = $(this).css("backgroundImage").split(",")
          , bgimg = img.concat(img[0]).splice(1).join(",");
          cycleBgImage(elem, bgimg);
        });
      });
  }($("#slideit")));
});
#slideit {
  width: 100%;
  height: 100%;
  display: block;
  opacity: 0.0;
  background-color: #000;
  background-image: url("http://lorempixel.com/400/400/cats/?1")
    , url("http://lorempixel.com/400/400/animals/?2")
    , url("http://lorempixel.com/400/400/nature/?3")
    , url("http://lorempixel.com/400/400/technics/?4")
    , url("http://lorempixel.com/400/400/city/?5");
  background-size: cover, 0px, 0px, 0px;
  -webkit-transition: background-image 3000ms linear;
  -moz-transition: background-image 3000ms linear;
  -ms-transition: background-image 3000ms linear;
  -o-transition: background-image 3000ms linear;
  transition: background-image 3000ms linear;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<body id="slideit"></body>

Upvotes: 1

Woody Payne
Woody Payne

Reputation: 605

Unfortunately CSS does not support the animation (via transition) of background images. Why? Actually, I'm not sure why. But it's enough to know they don't. Javascript works directly by extending CSS functionality. In short, what you want to do can't be done with Javascript without writing a very convoluted piece of code designed at hacking its functionality.

There is an easy work around using jQuery, however, which will actually make your source less complex too. Make the body relative, add each individual background image to the bottom of your source (to make them load after everything else) inside a named wrapper. Let's go with #backgrounds.

<style>
body{
    height:100%;
    position:relative
}
#backgrounds img{
    position:absolute;
    z-index:1; // this is important
    top:0;
    left:0;
    width:100%;
    height:100%;
    opacity:0;
    display:none;
}
#wrapper{
    position:relative;
    z-index:3; // again, this is important
}

</style>

We set the z-index of the wrapper to be higher than that of the images so that our content is in front of them, thus giving the illusion the images are background images. Change position:absolute to position:fixed if you want a background-attachment:fixed effect. I'm assuming you want their widths and heights to be that of the viewport; change them to whatever if not. We set the images to display:none to stop them all loading when the page loads. Yuck!

<div id="wrapper">

    all of your page are belong to us...

</div>
<div id="backgrounds">
    <img src="background/one.jpg" alt="">
    <img src="background/two.jpg" alt="">
    <img src="background/three.jpg" alt="">
</div>

And then simply cycle through each image using a counter based on the number of images (so you can easily cut and paste more images in later without any effort):

$(function(){
    var total = $('#backgrounds img').length;
    var counter = 1;


        function cycle(){
            // Makes old backgrounds appear beneath new ones
            $('#backgrounds img').css('z-index','1')
            // Set it to display and opacity 0 so we get the effect
            $('#backgrounds img:nth-child('+counter+')').css({'opacity':'0','display':'block','z-index':'2'})

            // Fade the background in
            $('#backgrounds img:nth-child('+counter+')').animate({'opacity':'1'},1500)

            // increase the counter
            counter++

            // make sure we're working within the quantity of images we have
            if( counter > total ){ counter = 1 }
        }
        cycle();
        setInterval(function(){cycle()},6000);

})

Upvotes: 2

Related Questions