Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove background image change flicker

I have a <div> with an image as a background. I have it so that whenever someone hovers over the <div>, the background image changes to some other image. The problem is, the first time when your mouse hovers over the <div>, the background image flickers as it loads and you see no image for few milliseconds.

How do I remove this flicker? How do I load the image for the hover before the user actually hovers over the <div> so the effect is immediate.

My code for changing the <div> background is very simple:

#someID{
    background-image: *image source*;
}
#someID:hover{
    background-image: *Another image source*
}

I know that there is a solution with putting the two desired images in one image and then play with the background position, but that's not an option here because I always set the background image to be like this:

image-size: 100% 100%;
like image 276
kfirba Avatar asked Mar 09 '13 20:03

kfirba


3 Answers

Within a window.load() function,

  • make sure all the images are loaded onto the page.
    FYI - You probably want to set each image's CSS position to absolute, with a Top:0px and Left:0px, all within a parent div that has a position:relative, with a certain width and height.

  • set display:none to the ones that should'nt be shown as DC_ pointed out

  • use jquery's hover method or click method to click on the image. Within the method function you choose, fadeOut() the current imag and fadeIn() the image that has a display:none associated to it.

like image 191
klewis Avatar answered Nov 20 '22 23:11

klewis


You can place an image tag somewhere in your DOM referencing the image you want to preload and give it a style of display:none; visibility: hidden;. You could also try using a JavaScript preloading solution but it wouldn't be as reliable.

like image 3
HellaMad Avatar answered Nov 20 '22 21:11

HellaMad


The flicker happens when the CSS changes and is reloaded. The flicker you see is the transition during the microseconds it takes to rewrite the CSS.

I recommend to layer your transition on top of another background. The flicker is really #someID element being fully transparent for a split second.

Pseudo code:

#underLayer {
     background-image: *image source*;
}

#someID {
    background-image: *image source*;
}

/* On change for #someID */
#someID:hover {
    background-image: *image source*;
}
<!-- first div acts as a base layer to show underneath during transition flicker -->
<div id="underLayer">
    <div id="someID"> This div changes on hover</div>
</div>
like image 1
jpostdesign Avatar answered Nov 20 '22 22:11

jpostdesign