Question: When I click a certain link I want the background-image to fadeOut, change to another image and then fadeIn. 

The code I have:

```
$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').css('background-image', 'url('+image+')');
})

```

I tried this:

```
$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000').fadeIn('3000').css('background-image', 'url(' + image + ')');
})

```

but this didn't work, what am I doing wrong? (I'm new to jQuery)

**EDIT:**

I solved this with Rory McCrossan answer:

```
$('.link').on('click',function(){
    var image = $(this).data('image');
    $('#div-with-the-bgimage').fadeOut('3000', function() {
        $(this).css('background-image', 'url('+image+')').fadeIn('3000');
    });
});

```

But now this fadesOut to a white background and and then fadesIn to the image, giving a sensation of a flash? Is there a way to load the image before?

Answer: 
Wouldn't it be much simpler if you append / remove a div with the image you want and not change anything in the background? Just an example:

```
 <div data-image="some-other-image.jpg" class="appendhere" style="position:relative">some content and an image background here</div>

```

Now using jQuery, you may put the image in the above data attribute on top, with 0 opacity, fade it in and out:

```
 $('.link').on('click',function(){
   var image = $(this).data('image');
   var appendcode = '<div class="appended" style="display:none;position:absolute;width:200px;height:200px;overflow:hidden"><img src="' + image + '"></div>';
   $('#div-with-the-bgimage').append(appendcode);
   $('.appended').css({'opacity': 0, 'display':'block', 'z-index': 999}).fadeIn('3000', function() {
     $(this).fadeOut('3000');
   });
});

```

I used some inline styles there to point you need to make the wrapper relative positioned and the appended absolute positioned and with a higher z-index, you can make it much more elegant by including these in your CSS of course.
U can combine `animate` and `opacity` or use `fadeOut` and `fadeIn` functions.

Check out this link [jsfiddle](http://jsfiddle.net/Academia/gfzLx739/) to see a working example using fadeOut and fadeIn.

U can also specify a unique img tag with data-gallery attribute storing multiple url's for images to toggle between all of them. Check this other link [jsfiddle](http://jsfiddle.net/Academia/7xtkgzm5/) to see a working example. Click on the button Toggle to change the image. 

Hope it useful!