Recently I created a website. On this website, there is a feature where 3 images change every 7 seconds for a total of 3 cycles.
The code snippet used for this functionality is as follows:
var swap;
function run(interval, frames) {
var int = 1;
function func() {
document.body.id = "b"+int;
int++;
if(int === frames) { int = 1; }
}
var swap = window.setInterval(func, interval);
}
run(7000, 3);
Additionally, here is the second part of the code (which I believe to be error-free):
$(window).scroll(function(){
//... your logic goes here...
$("body").css("background-image", "url(1.jpg)");
if(youWantToStopTheInterval){
window.clearInterval(swap);
$("body").css("background-image", "url(1.jpg)");
}
});
CSS styling related to the background images:
#b1 {
/* Location of the image */
background-image: url(1.jpg);
/* Background image is centered vertically and horizontally at all times */
background-position: center center;
/* Background image doesn't tile */
background-repeat: no-repeat;
/* Background image is fixed in the viewport so that it doesn't move when
the content's height is greater than the image's height */
background-attachment: fixed;
/* This is what makes the background image rescale based
on the container's size */
background-size: cover;
/* Set a background color that will be displayed
while the background image is loading */
background-color: #464646;
}
#b2 {
/* Location of the image */
background-image: url(2.jpg);
/* Background image is centered vertically and horizontally at all times */
background-position: center center;
/* Background image doesn't tile */
background-repeat: no-repeat;
/* Background image is fixed in the viewport so that it doesn't move when
the content's height is greater than the image's height */
background-attachment: fixed;
/* This is what makes the background image rescale based
on the container's size */
background-size: cover;
/* Set a background color that will be displayed
while the background image is loading */
background-color: #464646;
}
#b3 {
/* Location of the image */
background-image: url(3.jpg);
/* Background image is centered vertically and horizontally at all times */
background-position: center center;
/* Background image doesn't tile */
background-repeat: no-repeat;
/* Background image is fixed in the viewport so that it doesn't move when
the content's height is greater than the image's height */
background-attachment: fixed;
/* This is what makes the background image rescale based
on the container's size */
background-size: cover;
/* Set a background color that will be displayed
while the background image is loading */
background-color: #464646;
}
Upon refresh or page load, you may notice a brief moment of grey background before the images cycle properly. Any ideas why this happens or how it can be resolved?