Sunday, March 29, 2020

Html CSS background transition using jQuery

Supposing we have to animate body background-image change, this small code can help:

<script>
 
var bgs = ['background-image-1','background-image-2','background-image-3];/*Must be filled with images urls*/
var nbBgImages = 3; /*Must be changed if we have more or less then 3 images*/
</script>
Note:
background-image-1, background-image-2, background-image-1,....,background-image-N must have this form:
url(image-url)

Let's continue javascript and then we'll add a litte css style:
Assuming we are using jQuery we add this script inline or in separate js file:

 
(function($) {
var currentShowingBg = 1;
setInterval(changeBgImage, 7000);
function changeBgImage(){
$("body").css("background-image", bgs[currentShowingBg]);
++currentShowingBg;
if(currentShowingBg >= nbBgImages) currentShowingBg = 0;
}
})(jQuery);


all right now with js
Let's add transitions :
<style>
 
body{

background-repeat:no-repeat;>
background-position:center;
background-color:black !important;
-webkit-transition-property: background-image;
-webkit-transition-duration: 4.0s;
-webkit-transition-timing-function: ease-out;
}

</style>
Now it works ! you can stop here

Let's optimize !
There s a little shity problem with previous code: in case we have big images, latence time spend in images download will affect transitions.

A little trick is to load all images inside the html code but HIDDEN, then knowing that ready function of jquery launched only when DOM is loaded entierly we'll avoid the problem:
Let's add this html:

 
<div style="display:none">
<img src="image1"/>
<img src="image2"/>
<img src="image3"/>

</div>


all right.
See you in j2ee snippets that's better.