here’s a description of the issue I’m having:
The following script will rotate through five background image every 10 seconds; it works perfectly in IE, FF, and Safari – but in Chrome, the background image will only rotate once, and no further images are rotated, unless I refresh the browser via F5. Then all images are rotated on the expected interval, and all is right with the universe.
I’ve been pounding my brain on this one: for the rotation function, I’ve switched between setTimeout / setInterval, and for image-preloading good measure, I’ve swapped between $(window).load(function() / $(document).ready(function(), but nothing seems to do the trick – I always have to refresh Chrome in order for more than one image rotation to occur. Just to reiterate, Chrome will flip to the first image after the initial 10 seconds once the page loads, but after that, radio silence – no other images are rotated, unless the page is refreshed.
I’m using JQuery v1.6.2, and Chrome 13.0.782.112
Here’s the code, I’ve included the javascript, the HTML to load it, and the associated CSS for good measure.
Any insight would be greatly appreciated!
rotateBg.js (first create an array of the images paths, then preload, then rotate)
$(window).load(function(){
var imgArr = new Array( // relative paths of images
'./images/bg_neon.jpg',
'./images/bg_trees.jpg',
'./images/bg_dancing.jpg',
'./images/bg.jpg'
);
var preloadArr = new Array();
var i;
/* preload images */
for(i=0; i < imgArr.length; i++){
preloadArr[i] = new Image();
preloadArr[i].src = imgArr[i];
}
var currImg = 1;
var intID = setTimeout(changeImg, 10000);
/* image rotator */
function changeImg(){
$('.bg_image').animate({opacity: 0}, 1000, function(){
$(".bg_image").attr('src',preloadArr[currImg++%preloadArr.length].src);
}).animate({opacity: 1}, 1000);
}
});
index.html
<head>
<link rel="stylesheet" media="screen" type="text/css" href="./styles/home.css">
<script type="text/javascript" src="./scripts/jquery.js"></script>
<script type="text/javascript" src="./scripts/rotateBg.js"></script>
</head>
<body>
<img class="bg_image" src="./images/bg.jpg"/>
</body>
home.css (this is just used to keep the background proportional given screen resizing)
img.bg_image {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
z-index:-1;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px){
img.bg_image {
left: 50%;
margin-left: -512px; }
}
I tried your script in IE8, Safari and Chrome. It does not work for me in any browser. I can make it work though if I add setTimeout(changeImg, 10000); as the last line of the changeImg() function:
Cheers!