PDA

View Full Version : javascript background image and arrays



sniperman
09-03-2009, 10:46 AM
Hi everyone. I have a background image rotator script to change the background image on intervals. The only problem is that the image paths stored in the array fail to be called properly in the script. Can anyone tell me whether the method for calling the array is correct because i placed the array's string directly into the backgroundImage = value and that works fine.



images = new Array();
images[0] = "images/one.gif";
images[1] = "images/two.gif";
images[2] = "images/three.gif";
images[3] = "images/four.gif";
images[4] = "images/five.gif";
images[5] = "images/six.gif";
images[6] = "images/seven.gif";
images[7] = "images/eight.gif";


window.onload = function showDelay() {
setInterval ("changeBg('footer');", 5000);

}

var ns = (document.all)?false:true;
var intBack = 1;
i=0;
//function for dynamically switching the background image
function changeBg(divId) {
if (ns){
layerObject = document.getElementById(divId).style;
} else {
layerObject = eval(divId + ".style");
}
if (i==8) {i=0;}
layerObject.backgroundImage = 'url(images[i])';
i++;

}

thenajsays
09-03-2009, 01:11 PM
have you tried changing the file location to "/images/one.gif"?

sniperman
09-03-2009, 02:17 PM
i did try that but no difference. firefox shows no errors but FF's firebug shows
background-image: url(images[i]); so i assume the string is not being passed.

I don't believe the problem is variable scope.

I'm perplexed to be honest.

vwphillips
09-03-2009, 04:28 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
/*<![CDATA[*/
var images = new Array();
images[0] = "http://www.vicsjavascripts.org.uk/StdImages/One.gif";
images[1] = "http://www.vicsjavascripts.org.uk/StdImages/Two.gif";
images[2] = "http://www.vicsjavascripts.org.uk/StdImages/Three.gif";
images[3] = "http://www.vicsjavascripts.org.uk/StdImages/Four.gif";
images[4] = "http://www.vicsjavascripts.org.uk/StdImages/Five.gif";
images[5] = "http://www.vicsjavascripts.org.uk/StdImages/Six.gif";
images[6] = "http://www.vicsjavascripts.org.uk/StdImages/Seven.gif";
images[7] = "http://www.vicsjavascripts.org.uk/StdImages/Eight.gif";


window.onload = function showDelay() {
setInterval ("changeBg()", 5000);

}

var i=0;
//function for dynamically switching the background image
function changeBg(divId) {
if (i==8){
i=0;
}
document.getElementById('footer').style.backgroundImage = 'url('+images[i]+')';
i++;

}
/*]]>*/
</script></head>

<body>
<div id="footer" style="width:100px;height:100px;" ></div>
</body>

</html>