nina_berlini nina_berlini - 3 months ago 8
CSS Question

change only the background-image smooth without text in front of it

I have a website, where I want to change between images in the background very smoothly. This is my actual javaScript-code for it:

var bg=[
'images/best.jpg',
'images/61182.jpg',
'images/bg.jpg'
];

$('._container-1').css('background-image','url('+bg[2]+')');


window.setInterval(
function(){
img=bg.shift();bg.push(img);
document.getElementsByClassName('_container-1')[0].style.backgroundImage='url('+img+')';
},
10000
);


Now, I want to change the images very slowly. I have tried a lot with jQuery-fadeIn/fadeOut-methods like this:

window.setInterval(
function(){
img=bg.shift();
bg.push(img);

$('._container-1').fadeOut(600, function() {
$('._container-1').css('background-image','url('+img+')');
$('._container-1').fadeIn(600);
});

},
17000
);


The problem is, that there are buttons and text in the container and they changes with the images. I want that the text and buttons are in the front all the time, only the background should fadeIn/fadeOut. My english is not perfect, I hope you understand my problem.

Can somebody help me please?

nina_berlini

Answer

I have uses 2 elements as background to achieve the effect. Also check demo on https://jsfiddle.net/n380u3cy/1/

HTML:

<div class="container">
  <div class="background"></div>
  <div class="background"></div>
  <button>
    Test button
  </button>
</div>

CSS:

.container { position: relative; line-height: 100px; }
  .container > .background,
  .container > .background { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background-size: contain; z-index: 0; }

  .container > *:not(.background) { position: relative; z-index: 1; }

Javascript:

var bg=[
          'images/best.jpg',
          'images/61182.jpg',
          'images/bg.jpg'
       ];
var Transition = 1000;

$('.background').css('background-image','url('+bg[bg.length - 1]+')');
window.setInterval(
  function() {
    img=bg.shift();
    bg.push(img);

    var $Backgrounds = $('.background');
        $Backgrounds.eq(1).hide(0).css({
        'background-image': 'url('+img+')'
    }).fadeIn(Transition * .9);

    $Backgrounds.eq(0).show(0).fadeOut(Transition, function(){
        $(this).show(0).css({
        'background-image': 'url('+img+')'
      });
      $Backgrounds.eq(1).hide(0);
    });
  }, 2000
);