admin管理员组

文章数量:1025217

I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:

HTML

<div id="bg_left"></div>
<div id="bg_right"></div>

CSS body{ height:100%; }

#bg_left{
   height:100%;
   width:50%;
   left:0;
   position:fixed;
   background-position:left;
}
#bg_right{
    height:100%;
    width:50%;
    right:0;
    position:fixed;
    background-image:url(.png);
    background-position:right;
}  

JAVA SCRIPT

 function carousel_bg(id) {
     var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; 
     var img1 = bgimgs[id];
     var img2 = bgimgs[id+1];
     var cnt = 2; 

     $('#bg_left').css("background-image", "url(/"+img1+")");
     $('#bg_right').css("background-image", "url(/"+img2+")");

     id = id + 1;
     if (id==cnt) id = 0;

     setTimeout("carousel_bg("+id+")", 10000); 
 }

 $(document).ready(function() {
        carousel_bg(0);     
 });

​ The background-images should be changing randomly, but they don't even change at all.

I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:

HTML

<div id="bg_left"></div>
<div id="bg_right"></div>

CSS body{ height:100%; }

#bg_left{
   height:100%;
   width:50%;
   left:0;
   position:fixed;
   background-position:left;
}
#bg_right{
    height:100%;
    width:50%;
    right:0;
    position:fixed;
    background-image:url(http://presotto.daterrawebdev./d/img/pp_hey_you_bg.png);
    background-position:right;
}  

JAVA SCRIPT

 function carousel_bg(id) {
     var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; 
     var img1 = bgimgs[id];
     var img2 = bgimgs[id+1];
     var cnt = 2; 

     $('#bg_left').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img1+")");
     $('#bg_right').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img2+")");

     id = id + 1;
     if (id==cnt) id = 0;

     setTimeout("carousel_bg("+id+")", 10000); 
 }

 $(document).ready(function() {
        carousel_bg(0);     
 });

​ The background-images should be changing randomly, but they don't even change at all.

Share Improve this question edited Aug 20, 2013 at 18:28 Eric Leschinski 154k96 gold badges422 silver badges337 bronze badges asked Dec 12, 2012 at 19:10 Vinicius SantanaVinicius Santana 4,1063 gold badges27 silver badges44 bronze badges 6
  • 2 What edits did you just make? Please specify when others are actively trying to work on it. – justacoder Commented Dec 12, 2012 at 19:41
  • Sorry. I changed the var img for img1 and added one more variable and named it img2. I also changed the $(body').css("backgrou... to $('#bg_left').css(".. and added one more action for the #bg_right. – Vinicius Santana Commented Dec 12, 2012 at 19:49
  • 1 Please do not "bump" your question by adding "UNSOLVED:" to the title. Unsolved questions are already visually indicated. – Sparky Commented Dec 12, 2012 at 19:49
  • ok.. no problem. Got it. – Vinicius Santana Commented Dec 12, 2012 at 19:52
  • 1 So... just trying to understand whats happening here. Is anything else that has to be done before we get to talk about the issue with the code? Im not very familiar with StackOverflow rules but I'm ok with them. – Vinicius Santana Commented Dec 12, 2012 at 19:59
 |  Show 1 more ment

3 Answers 3

Reset to default 5

OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle/jfriend00/awVYP/

And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle/jfriend00/LVGNN/

    function carousel_bg(id) {
        var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..

        function next() {
            if (id >= bgimgs.length) {
                id = 0;
            }
            var img1 = bgimgs[id];
            id++;
            if (id >= bgimgs.length){
                id = 0;
            }
            var img2 = bgimgs[id];

            $('#bg_left').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img1+")");
            $('#bg_right').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img2+")");
            setTimeout(next, 1000);
        }
        next();
    }

    $(document).ready(function() {
            carousel_bg(0);     
    });

Previous ments on earlier version so of the OP's code:

$('#body')

should be:

$('body')

or even faster:

$(document.body)

Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?

For testing I added another image to the array so that we got some distinction in the sorting.

function carousel_bg(id) {
    var bgimgs = [  'http://presotto.daterrawebdev./d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev./d/img/burningman_bg.png', 'http://gallery.orobouros/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
    var img1 = bgimgs[id+1];
    var img2 = bgimgs[id];
    var cnt = bgimgs.length; // change this number when adding images..

    $('#bg_left').css("background-image", "url("+img1+")");
    $('#bg_right').css("background-image", "url("+img2+")");

    id = id + 1;
    if (id== (cnt - 1) ) id = 0;

    setTimeout("carousel_bg("+id+")", 10000);
}

Two changes here:

  1. For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
  2. In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).

While this code does loop through your array, it's not random. That's another topic.

For those not using JQuery, simply do the following:

document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";

I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:

HTML

<div id="bg_left"></div>
<div id="bg_right"></div>

CSS body{ height:100%; }

#bg_left{
   height:100%;
   width:50%;
   left:0;
   position:fixed;
   background-position:left;
}
#bg_right{
    height:100%;
    width:50%;
    right:0;
    position:fixed;
    background-image:url(.png);
    background-position:right;
}  

JAVA SCRIPT

 function carousel_bg(id) {
     var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; 
     var img1 = bgimgs[id];
     var img2 = bgimgs[id+1];
     var cnt = 2; 

     $('#bg_left').css("background-image", "url(/"+img1+")");
     $('#bg_right').css("background-image", "url(/"+img2+")");

     id = id + 1;
     if (id==cnt) id = 0;

     setTimeout("carousel_bg("+id+")", 10000); 
 }

 $(document).ready(function() {
        carousel_bg(0);     
 });

​ The background-images should be changing randomly, but they don't even change at all.

I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:

HTML

<div id="bg_left"></div>
<div id="bg_right"></div>

CSS body{ height:100%; }

#bg_left{
   height:100%;
   width:50%;
   left:0;
   position:fixed;
   background-position:left;
}
#bg_right{
    height:100%;
    width:50%;
    right:0;
    position:fixed;
    background-image:url(http://presotto.daterrawebdev./d/img/pp_hey_you_bg.png);
    background-position:right;
}  

JAVA SCRIPT

 function carousel_bg(id) {
     var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; 
     var img1 = bgimgs[id];
     var img2 = bgimgs[id+1];
     var cnt = 2; 

     $('#bg_left').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img1+")");
     $('#bg_right').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img2+")");

     id = id + 1;
     if (id==cnt) id = 0;

     setTimeout("carousel_bg("+id+")", 10000); 
 }

 $(document).ready(function() {
        carousel_bg(0);     
 });

​ The background-images should be changing randomly, but they don't even change at all.

Share Improve this question edited Aug 20, 2013 at 18:28 Eric Leschinski 154k96 gold badges422 silver badges337 bronze badges asked Dec 12, 2012 at 19:10 Vinicius SantanaVinicius Santana 4,1063 gold badges27 silver badges44 bronze badges 6
  • 2 What edits did you just make? Please specify when others are actively trying to work on it. – justacoder Commented Dec 12, 2012 at 19:41
  • Sorry. I changed the var img for img1 and added one more variable and named it img2. I also changed the $(body').css("backgrou... to $('#bg_left').css(".. and added one more action for the #bg_right. – Vinicius Santana Commented Dec 12, 2012 at 19:49
  • 1 Please do not "bump" your question by adding "UNSOLVED:" to the title. Unsolved questions are already visually indicated. – Sparky Commented Dec 12, 2012 at 19:49
  • ok.. no problem. Got it. – Vinicius Santana Commented Dec 12, 2012 at 19:52
  • 1 So... just trying to understand whats happening here. Is anything else that has to be done before we get to talk about the issue with the code? Im not very familiar with StackOverflow rules but I'm ok with them. – Vinicius Santana Commented Dec 12, 2012 at 19:59
 |  Show 1 more ment

3 Answers 3

Reset to default 5

OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle/jfriend00/awVYP/

And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle/jfriend00/LVGNN/

    function carousel_bg(id) {
        var bgimgs = [  'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..

        function next() {
            if (id >= bgimgs.length) {
                id = 0;
            }
            var img1 = bgimgs[id];
            id++;
            if (id >= bgimgs.length){
                id = 0;
            }
            var img2 = bgimgs[id];

            $('#bg_left').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img1+")");
            $('#bg_right').css("background-image", "url(http://presotto.daterrawebdev./d/img/"+img2+")");
            setTimeout(next, 1000);
        }
        next();
    }

    $(document).ready(function() {
            carousel_bg(0);     
    });

Previous ments on earlier version so of the OP's code:

$('#body')

should be:

$('body')

or even faster:

$(document.body)

Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?

For testing I added another image to the array so that we got some distinction in the sorting.

function carousel_bg(id) {
    var bgimgs = [  'http://presotto.daterrawebdev./d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev./d/img/burningman_bg.png', 'http://gallery.orobouros/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
    var img1 = bgimgs[id+1];
    var img2 = bgimgs[id];
    var cnt = bgimgs.length; // change this number when adding images..

    $('#bg_left').css("background-image", "url("+img1+")");
    $('#bg_right').css("background-image", "url("+img2+")");

    id = id + 1;
    if (id== (cnt - 1) ) id = 0;

    setTimeout("carousel_bg("+id+")", 10000);
}

Two changes here:

  1. For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
  2. In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).

While this code does loop through your array, it's not random. That's another topic.

For those not using JQuery, simply do the following:

document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";

本文标签: jQueryJavascriptHow to change the background of a div tag every x secondsStack Overflow