0

My idea was to make a HTML page that would change its background every 3 seconds or so. I started out simple, with just two possible variations and was intending to move on to more possible background images later. For example, every time 3 seconds pass, some global temp variable (if global scope exists in JS or HTML at all, like in C++) counting number of times the background changed would increase for 1, which would, in the end, determine what the next background would be.

For testing and learning purposes, I started out with two backgrounds determined by if condition:

<script>

function diffBg (){         

        var loc="url('1.jpg')";
        var loc2="url('2.jpg')";

        if (document.body.style.backgroundImage == loc)
        {
            document.body.style.backgroundImage = loc2;
        }
        else
        {
            document.body.style.backgroundImage = loc;
        }
    }

</script>

The function would be triggered by body event:

<body onload="setInterval(diffBg,3000)">

When loaded, page background is at first white. After 3 seconds, the background changes, never to be changed again.

I assume the error has to do with body loading only once, thus the function is being called only once. How could I fix this?

I'm a JS and HTML beginner. I've only programmed in C++ and I guess I use my "C++ logic" with everything I do.

Every help is greatly appreciated. Thanks in advance.

Edit: Post What's the easiest way to call a function every 5 seconds in jQuery? does not help me at all. I tried mentioned methods and none of them worked.

Community
  • 1
  • 1
0lt
  • 283
  • 2
  • 13
  • Actually your function is called every 3 seconds but the condition in the `if` statement will evaluate to `false` because you are using a relative path while your browser transforms it in an absolute path when setting `document.body.style.backgroundImage`. – B0Andrew Dec 10 '14 at 11:20
  • I replaced relative with absolute paths, now the background is white all the time. – 0lt Dec 10 '14 at 11:30
  • Open developer tools in your browser (generally with `F12` or right-click in window and `Inspect element`) and see what errors do you receive. Depending on the browser you use learn how to add breakpoints and debug your code. – B0Andrew Dec 10 '14 at 11:37

0 Answers0