Reputation: 801
I have somewhat complex div structure on my page and I want to switch some images (on hover), but I can't directly set hover with css because the image I want to make hover on is behind another transparent image. Therefore I have created transparent overlay on the top. When the overlay is hovered, specified div's background is switched.
HTML:
<div id="image"></div>
<div id="overlay"></div>
CSS:
#image {
position: absolute;
width: 300px;
height: 300px;
background: url(myImage.jpg);
}
#overlay {
position: absolute;
width: 300px;
height: 300px;
}
and here is jQuery doing the switching:
$(function() {
$("#overlay").hover(function() {
$("#image").css({
"background": "url(myNewImage.jpg)"
});
}, function() {
$("#image").css({
"background": "url(myImage.jpg)"
});
});
});
It switches the images without problem. Issue is that there is a small delay while the images are switched so for a moment (less than second) you are able to see blank background (when #image div is not filled with either image).
On the other hand when you use plain CSS without jQuery to switch images like this (which is not possible in this case) then there is no such delay.
So, using jQuery, how would you prevent this delay from taking place? Or is there a better way to solve this?
Upvotes: 3
Views: 155
Reputation: 105863
what you need is to set multiple background image, so both images are loaded.
on hover , switch background-position
.
Something similar to this:
$(function() {
$("#overlay").hover(function() {
$("#image").css({
"background": "url(myNewImage.jpg) top left, url(myImage.jpg) 9999px 9999px"
});
}, function() {
$("#image").css({
"background": "url(myNewImage.jpg) 9999px 9999px, url(myImage.jpg) top left"
});
});
});
#image {
position: absolute;
width: 300px;
height: 300px;
background:url(myNewImage.jpg) 9999px 9999px, url(myImage.jpg) top left;
}
Upvotes: 1
Reputation: 1801
Your problem is the image you're loading in via jQuery is not preloaded. When you switch out the image, the image takes a second to download. When you have image URLs in CSS, all of those images are downloaded with the stylesheet. The solution to your problem is to preload your images.
Upvotes: 4
Reputation: 1216
I am not 100% sure as I don't know the complete situation but from what information you are providing it should be possible with pure CSS as well:
#overlay:hover #image {
background: url(anotherImage.jpg);
}
Regarding the delay in displaying the pictures, you could use a sprite. Place both pictures in one file (e.g. above eachother) and when hovering, change the background image position.
Upvotes: 1