0

I'm coding a website where one of the briefs is to have the background images change between 6 or more different images. The background has to be fixed in place and the text scrolls over it. This part I have done with the below Javascript

function RotatingBackground() {
var curImgId = 6;
var numberOfImages = 6; // Change this to the number of background images
var my_image0 = new Image(); my_image0.src = 'background_images/0.jpg';
var my_image1 = new Image(); my_image1.src = 'background_images/1.jpg';
var my_image2 = new Image(); my_image2.src = 'background_images/2.jpg';
var my_image3 = new Image(); my_image3.src = 'background_images/3.jpg';
var my_image4 = new Image(); my_image4.src = 'background_images/4.jpg';
var my_image5 = new Image(); my_image5.src = 'background_images/5.jpg';
var my_image6 = new Image(); my_image6.src = 'background_images/6.jpg';
if (curImgId > 6006) { curImgId = 6;}
window.setInterval(function() {
    $('body').css('background-image','url(background_images/' + curImgId + '.jpg)');
    curImgId = (curImgId + 1) % numberOfImages;
}, 5 * 1000);

}

I call the code on Body Load as below

<body style="background: url(./background_images/0.jpg) no-repeat center center fixed; background-size: cover; margin:0; padding:0;" onLoad="RotatingBackground()">

The issue I have is that they abruptly change, taking about a quarter to a half second to load, despite an attempt to pre-load the images at the top of the JS function.

I have tried various cross-fade techniques, but they either don't scale the image correctly, or they don't keep the background fixed. Is there an easy way using a little CSS or JS (or even JQuery) to smoothly transition from one image to another? (Emphasis on the easy as I'm not brilliant with javascript).

  • We need a working example of your current code. – Black Apr 23 '17 at 16:21
  • Why do you need `if (curImgId > 6006) { curImgId = 6;}` this makes no sense at all. – Black Apr 23 '17 at 16:22
  • It kept adding 1 to the count and stopped changing the image if you idled on a page for a couple of hours. This was my work around, but it's redundant now as I altered the code. That code is the only code I use to alter the background image. I'll upate it with the body CSS if you want, but the rest of the site just displays text on the page. – John Westerman Apr 23 '17 at 16:25
  • 'body { font-size:16px; font-weight:normal; font-family: 'arial', Verdana, Arial, Sans-Serif; color: #2b1b17; text-align: center; padding:0!important; margin:0!important;}' – John Westerman Apr 23 '17 at 16:30
  • try this https://jsfiddle.net/dalinhuang/vkdcw379/ – Dalin Huang Apr 23 '17 at 16:35

0 Answers0