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!
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.
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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With