Fade effect on image exchange with jQuery

3

The following code makes an "image fader" in a div that I have in my document. However, the effect is very 'dry', I would like to have a transition during the exchange of images, like the fade effect of jQuery.

var images = ['image-1.jpg','image-2.jpg','image-3.jpg','image-4.jpg','image-5.jpg','image-6.jpg'],
   index = 0,
   maxImages = images.length - 1;
var timer = setInterval(function() {
   var curImage = images[index];
   index = (index == maxImages) ? 0 : ++index;
   $('.header').css({'background-image':'url(./img/'+curImage+')'});
}, 1500);

How could I do it?

Follow a fiddle with a small example .

    
asked by anonymous 26.03.2014 / 02:16

3 answers

2

On line:

$('.header').css({'background-image':'url(./img/'+curImage+')'});

You can put a fadeout effect and fade in:

$('.header').fadeout().css({'background-image':'url(./img/'+curImage+')'}).fadein();
    
26.03.2014 / 02:24
5

Use CSS property transition: background 500ms ease directly in the .header or javascript class:

$('.header').css({
    'background-image': 'url('+curImage+')',
    'transition': 'background 500ms ease'
});
    
26.03.2014 / 03:43
3

Add transition: background-image 300ms; to your CSS file. It is better to add in the CSS file than to add CSS rules via javascript.

Example

CSS

.header{
    background: #333 url('http://flaticons.net/icons/Emotions/Cheeky.png') no-repeat;
    width: 100%;
    height: 262px;
    transition: background-image 300ms; // linha nova!
                                        // 300ms é a velocidade (em milisegundos) da transição
}

For older browsers that do not support CSS transitions you can use this:

Example

HTML

<div class="header">
    <div class="headerImage"></div>
</div>

CSS

.header {
    width: 100%;
    height: 262px;
    background: #333
}
.headerImage {
    background: url('http://flaticons.net/icons/Emotions/Cheeky.png') no-repeat;
    width: 100%;
    height: 100%;
}

Javascript

var timer = setInterval(function () {
    var curImage = images[index];
    index = (index == maxImages) ? 0 : ++index;
    var $headerImage = $('.headerImage');
    $headerImage.animate({
        opacity: 0
    }, function () {
        $headerImage.css({
            'background-image': 'url(' + curImage + ')'
        });
        $headerImage.animate({
            opacity: 1
        })
    });
}, 1500);
    
26.03.2014 / 10:11