Skip to content

Instantly share code, notes, and snippets.

@dusk0r
Last active September 3, 2020 16:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dusk0r/3d5b46b3ed43aae88b2d to your computer and use it in GitHub Desktop.
Save dusk0r/3d5b46b3ed43aae88b2d to your computer and use it in GitHub Desktop.
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