javascriptjqueryfadeinfadeout

Jquery Fade in Fade out


I have the following code:

Code:

$(document).ready(function(){
var header = $('body');

var backgrounds = new Array(
'url(/1.jpg)'
, 'url(/2.jpg)'
, 'url(/1.jpg)'

);

var current = 0;

function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 5000);

header.css('background-image', backgrounds[0]);
});

What can I add to the above code so there is a "smooth" transition between background images. I prefer not to use a plugin.

THANKS :)


Solution

  • If you want to crossfade the slides, you can place a duplicate of the image on top and fade it out as the next slide changes underneath.

    $(document).ready(function(){
      var image = $('.wrap');
      var fader = $('.fader');
    
      var backgrounds = new Array(
        'url(https://via.placeholder.com/480&text=Slide+1)'
        ,'url(https://via.placeholder.com/480&text=Slide+2)'
        ,'url(https://via.placeholder.com/480&text=Slide+3)'
      );
    
      var current = 0;
      function nextBackground() {
        // Change the background image while
        // creating a duplicate of image and 
        // fade it out
        fader.css('background-image', backgrounds[current]).fadeOut(function() {
          fader.css('background-image', '').show();
        });
        
        current++;
        current = current % backgrounds.length;
        
        image.css('background-image', backgrounds[current]);
      }
      setInterval(nextBackground, 2000);
    
      image.css('background-image', backgrounds[0]);
    });
    .wrap, .fader {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      background-size: contain;
      background-repeat: no-repeat;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="wrap">
      <div class="fader"></div>
    </div>