Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery change div background-image with fadeIn/Out

I'm trying to create a fadeIn/Out effect on a site I created (edit: site url deleted)

Everything works great except when you click on one of the colors in the color palette, it replaces the image with no effect.

This is the small script I wrote, which is triggered onclick on one of the colors.

function changeImage(newColor) {

    //var previousImage = $('#image-holder').css("background-image");

    $('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')");
};

I tried playing with $('#image-holder').fadeOut(1500) and then $('#image-holder').fadeIn(1500) but it acts funny... it double fades the image.

$('#image-holder').css("background", "url('images/design-" + newColor + ".jpg')").fadeOut(function(){$(this).fadeIn()});

What I would like to achieve is onclick on a color box, the current background image will fadeout while the new background image will fade in.

I know it's easier to achieve that if I'd used two <img src="" /> and switch their display/visibility but I unfortunately I can't alter the HTML that much so I'm looking for a jQuery based solution.

Appreciate the help!

like image 518
Lior Iluz Avatar asked Dec 22 '11 23:12

Lior Iluz


People also ask

What is the syntax of jQuery fadeIn () method?

The jQuery fadeIn() method is used to fade in a hidden element. Syntax: $(selector).fadeIn(speed,callback); The optional speed parameter specifies the duration of the effect.

Can you put a background image in a div?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.


2 Answers

This was the only reasonable thing I found to fade a background image.

<div id="foo">
  <!-- some content here -->
</div>

Your CSS; now enhanced with CSS3 transition.

#foo {
  background-image: url('a.jpg');
  transition: background 1s linear;
}

Now swap out the background

$("#foo").css("background-image", "url(b.jpg)");

Or do it with native javascript

document.querySelector("#foo").style.backgroundImage = "url(b.jpg)";

Voilà, it fades!


Obvious disclaimer: if your browser doesn't support the CSS3 transition property, this won't work.

like image 99
Mulan Avatar answered Oct 31 '22 08:10

Mulan


The solution that worked for me:

var image = $('#image-holder');
    image.fadeOut(1000, function () {
        image.css("background", "url('images/design-" + newColor + ".jpg')");
        image.fadeIn(1000);
    });
like image 10
Lior Iluz Avatar answered Oct 31 '22 07:10

Lior Iluz