I have a background-image that must be animated through fadein and fadeout effect on hover event. How I can do that?
Asked
Active
Viewed 1.2k times
0
-
provide the code that you have tried or place the fiddle link. – Praveen Jul 18 '13 at 05:09
-
1@user1671639: Not "or." Code must always be in the question itself. http://jsfiddle.net links are a useful *adjunct*, not a substitute. – T.J. Crowder Jul 18 '13 at 05:10
-
@T.J.Crowder Right. I forget it. Here when adding jsfiddle link without code, SO gives an error message. Thanks for pointing it. – Praveen Jul 18 '13 at 05:16
-
1Also you can try using [css3 transition](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions). – Praveen Jul 18 '13 at 05:20
-
but transition not supported by ie8 ( – user2560165 Jul 18 '13 at 05:36
-
http://stackoverflow.com/questions/6890218/css-background-opacity Second answer has what you need. – grmmph Jul 18 '13 at 06:02
1 Answers
7
HTML:
<div></div>
CSS:
div {
width:200px;
height:200px;
background-image:url(http://dummyimage.com/100x100/000/fff);
}
jQuery:
$('div').hover(function () {
$(this).stop().fadeOut("1000", function () {
$(this).css("background", "url('http://dummyimage.com/100x100/000/ff0000')").fadeIn(1000);
});
}, function () {
$(this).stop().fadeOut("1000", function () {
$(this).css("background", "url('http://dummyimage.com/100x100/000/fff')").fadeIn(1000);
});
});
Check this fiddle1.
Incase if you wish to it using CSS3 transition then,
change the CSS
like this
div {
height: 200px;
width: 200px;
color: black;
background-image:url(http://dummyimage.com/100x100/000/fff);
transition: background-image 1s linear;
-moz-transition: background-image 1s linear;
-webkit-transition: background-image 1s linear;
-ms-transition: background-image 1s linear;
}
div:hover {
background-image:url(http://dummyimage.com/100x100/000/ff0000);
}

Praveen
- 55,303
- 33
- 133
- 164