Lisa Schumann
Lisa Schumann

Reputation: 127

Changing background-images with a fade inbetween

I'm trying to change the background images of my hero section with JS. The loop is working but I'm not sure how to have one image fade into the next.

The way that it is currently set up makes it fade to white (the background colour) inbetween changes, rather than fading from one image to the next.

var images = ["../images/winter.jpeg", "../images/spring.jpeg", "../images/summer.jpeg", "../images/welcome.jpeg"];
var index = 0;

function changeBackground() {

  index = (index + 1 < images.length) ? index + 1 : 0;

  $('.hero').fadeOut(0, function () {

    $(this).css('background-image', 'url(' + images[index] + ')')

    $(this).fadeIn(0);

  });
};

var timer = null;

function startSetInterval() {
  timer = setInterval(changeBackground, 2000);
}
// start function on page load
startSetInterval();

$('.link-block-animation').hover(
  function () {
    clearInterval(timer);
  },
  function () {
    timer = setInterval(changeBackground, 2000);
  });

Upvotes: 1

Views: 74

Answers (1)

Klaassiek
Klaassiek

Reputation: 2906

One thing you could do is use absolute positioning on the .hero elements. Every time you want to change the background, you can then insert a new .hero with display:none on top of the old .hero. For absolute positioning to work you can add a container with position:relative. That way, you can be sure that all the .hero elements are at the exact same position. So your html and css could look like this:

<style>
.container{
    position:relative;
    height:100px;
    width:100px;
}
.hero{
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}
</style>
<div class="container">
    <div class="hero"></div>
</div>

Now, using javascript, you can add a .hero to the container, which will show on top. Since we want it to fade, we first set display to none, then fade it in. After fading in we can remove the old .hero. Something like this:

var index = 0;

$('.hero').css('background-image', 'url(' + images[index] + ')');

function changeBackground() {
    var oldHero = $('.hero');
    var newHero = $('<div class="hero"></div>');
    index = (index + 1 < images.length) ? index + 1 : 0;
    newHero.css('display','none');
    newHero.css('background-image', 'url(' + images[index] + ')');
    $('.container').append(newHero);
    newHero.fadeIn(1000,function(){
        oldHero.remove();
    });
};

Does that come close to what you need?

Upvotes: 1

Related Questions