Search code examples
javascriptanimationjquery-animatebackground-imagetimed

Making background fade in using Javascript


Hello below is my JS code for a changing background image every 30 seconds. I have this example code too from research, can somebody please please please show me how to integrate the example code into my JS, so the changing image fades in as I simply have no clue where to start and feel completely lost.

My JS

<script>
bgArr = ['images/bg1.jpg', 'images/bg2.jpg', 'images/bg3.jpg'];
bgCur = 0;
backgroundSwitch = function()
{
if (bgCur == bgArr.length) bgCur = 0;
document.body.style.backgroundImage = 'url('+ bgArr[bgCur++]+ ')';
}
window.setInterval(backgroundSwitch, 30000); // Switch every 30 seconds.
</script>

Example JS that I want to integrate

var img = document.getElementById("fade");

var fadeLength = 5500;
var opacity = 0;
 var startTime = Date.now();

requestAnimationFrame(function me() { 
// It's faded in, stop animating!
if (opacity >= 1) {
   return;   
}

opacity = (Date.now() - startTime) / fadeLength;
img.textContent = opacity;    
img.style.opacity = opacity;        
requestAnimationFrame(me);
});

Also is there a way to fit the background to the browser window within the javascript without using css?

Thank you and somebody please help!


Solution

  • One solution here is to use CSS transitions. No JS transition needed.

    transition: background-image 6s;
    

    Example