I want to crossfade/transition background images through hovering the element. Is is possible?
I have a DIV element that has a background image but when you hover it, the background image changes with a transition/crossfade effect. On my Stylesheet i have assigned a class for hover state.
Here is the normal or non-hover state of DIV.
#crossfade DIV{
width: 100px;
height: 100px;
background-image: url('img/bg.jpg');
}
Below is the hover state class of DIV.
#crossfade DIV.hovered{
background-image: url('img/bg-1.jpg');
}
Then my jquery script below:
$(function(){
$('#crossfade').find('DIV').hover(function(){
$(this).addClass('hovered');
}, function(){
$(this).removeClass('hovered');
});
});
My script just simple switch the background image. Now what i want is to give it a transition effect or more like fadeIn/fadeOut effect. Like as the previous background image is fading out, the next background image is also fading In.
Any idea how to do this? Is it possible?
Thanks 🙂
I spent quite some time troubleshooting this as it interested me as well. Learnt a lot so thought I’d share it with you.
First: I don’t believe you can cross-fade background images using addClass and removeClass because you can’t logistically fade an element in and out at the same time. (If I’m wrong about this please someone school me).
Just so that you know that I know what you’re wanting, I successfully got the following to work:
However, this DOESN’T resolve your issue, which is creating a cross-fade of 2 images.
You will see that the fadeOut runs first, then the new class is added, then the fadeIn is run, and the first class is removed. You can’t run the fadeOut and fadeIn (which would create the cross-fade you’re looking for) at the same time because if you remove the first class before the fadeOut is finished, it interrupts the animation.
Here is a solution that I believe will work for you.
HTML:
jQuery:
Note: Be sure to target the div for your hover function; targeting the image results in some bizarre behaviour.
(This solution assumes you wanted the image to crossfade when you hover and then crossfade back to the original when you un-hover. Changing the function to fadeOut will work as a once-off if that’s what you want).
If you were specifying background images because you need other content to sit in front, this is easily solved using z-index and a containing div (plus the jQuery above).
HTML:
CSS: