Create a gist now

Instantly share code, notes, and snippets.

Changing Background Images using jQuery
<html>
<head>
<style type="text/css">
.bgimage {
position: fixed;
background-repeat: no-repeat;
background-position: center;
background-size: cover;
background-color: black;
width: 100%;
height: 100%;
}
#bgimage1 {
/* Initiales Bild */
background-image: url(bg.1.jpg);
}
#bgimage2 {
display: none;
}
</style>
<script type="text/javascript">
function fadeImages() {
var bgImages = ["bg.1.jpg", "bg.2.jpg", "bg.3.jpg", "bg.4.jpg"];
var layer1 = $("#bgimage1");
var layer2 = $("#bgimage2");
var counter = 0;
var fadeDuration = 2000;
var keepImageDuration = 5000;
function crossFade() {
if (counter % 2 === 0) {
layer2.css("background-image", "url(" + bgImages[(counter + 1) % bgImages.length] + ")");
layer2.fadeIn(fadeDuration, function () {
setTimeout(crossFade, keepImageDuration);
});
} else {
layer1.css("background-image", "url(" + bgImages[(counter + 1) % bgImages.length] + ")");
layer2.fadeOut(fadeDuration, function () {
setTimeout(crossFade, keepImageDuration);
});
}
counter++;
};
setTimeout(crossFade, keepImageDuration);
}
$().ready(function () {
fadeImages();
});
</script>
</head>
<body>
<div class="bgimage" id="bgimage1">
</div>
<div class="bgimage" id="bgimage2">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment