I’m trying to switch the background image of an element (e.g. body) when hovering another (e.g. nav), having some sort of fade transition between the two images using jQuery.
I’ve been reading similar questions at stackoverflow and tried almost every example without much luck.
Resources
- index.html
- styles.css
- scripts.js
- background.png
- background-hover.png
Snippets
index.html
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
styles.css
body {
background: url('background.jpg') no-repeat;
}
scripts.js
$('nav')
.mouseenter(function(){
$('body').css("background", "url('background-hover.jpg') no-repeat");
})
.mouseleave(function(){
$('body').css("background", "url('background.jpg') no-repeat");
});
Any advice would be greatly appreciated. Thanks much in advance.
If you want a fade transition inbetween your backgrounds, it can’t be done by solely changing the
background-imagefrom one to another. You’ll need to at least create one other element which you can fadeIn and out. For example like this:Example: http://jsfiddle.net/niklasvh/bXMKJ/
If you want the current image to fadeOut while the other one fades in, then you will need to have 2 dummy elements, because you can’t fade the
body(at least with the results you’d expect).If you just want the
background-imageto change from one to another, then you can fix your code by removeing the;at the end of the mouseenter function, like this:Example: http://jsfiddle.net/niklasvh/sC5rd/