1

I have the following piece of JS which toggles the BG color from red to green and so on.

function blink() {
            var currentColor = 'red';
            setInterval(function () {
                document.body.style.backgroundColor = currentColor;
                currentColor = currentColor === 'red' ? 'green' : 'red';
            }, 1000);
        };

Is there anyway to change the colours to images so it toggles between two images instead of two colours?

I have tried the following but without success:

function toggleBG() {
            var currentColor = "Images/tableBGRed.gif";
            setInterval(function () {
                var myDiv = document.getElementById("testDiv");
                myDiv.style.backgroundImage = "url('" + currentColor + "')";
                currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')";
            }, 1000);
        };

Something wrong with the syntax?

sd_dracula
  • 3,796
  • 28
  • 87
  • 158
  • have you set a height and width of your div as without content a div will be collapsed and will not be visible unless it has content or a height and width set. – Squirrel5853 Sep 27 '13 at 12:14
  • This also might help: http://stackoverflow.com/questions/10867503/change-background-image-in-body Another thing you could try is just getting rid of the ?: syntax and using an actual if/else. I've never trusted that syntax myself. – Drew Sep 27 '13 at 12:15
  • Yes the div has content and with the toggleBG() function above the BG changes to red and just stays red, never actually changes to "url('Images/tableBG.gif')" it seems – sd_dracula Sep 27 '13 at 12:20

2 Answers2

2
currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')"; 

will cause the string to become something like "url(url(' Images/cat.gif '))", which is not a valid value for myDiv.style.backgroundImage,

since you've got myDiv.style.backgroundImage = "url('" + currentColor + "')"; in the previous line.

Updates:

You can use CSS3 to make it look like an animation (fading):

#testDiv{
-webkit-transition: all 0.1s ease;
-moz-transition: all 0.1s ease;
-ms-transition: all 0.1s ease;
-o-transition: all 0.1s ease;
transition: all 0.1s ease;
}
Archy Will He 何魏奇
  • 9,589
  • 4
  • 34
  • 50
1

To me it seems your code creates a backgroundimage as

url('url('Images/xxx.gif')')

Try

function toggleBG() {
    var currentColor = "url('Images/tableBGRed.gif')";
    setInterval(function () {
        var myDiv = document.getElementById("testDiv");
        myDiv.style.backgroundImage = currentColor;
        currentColor = currentColor === "url('Images/tableBGRed.gif')" ? "url('Images/tableBG.gif')" : "url('Images/tableBGRed.gif')";
    }, 1000);
};
user2764860
  • 103
  • 6