kfirba
kfirba

Reputation: 5441

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%;

Upvotes: 7

Views: 9311

Answers (4)

Paskainos
Paskainos

Reputation: 1

I had a very similar issue. I believe you'll find it's related to this: cubiq.org/you-shall-not-flicker

Simple solution (from the article): -webkit-transform:translate3d(0,0,0).

Upvotes: 0

jpostdesign
jpostdesign

Reputation: 2608

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>

Upvotes: 1

klewis
klewis

Reputation: 8350

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.

Upvotes: 5

HellaMad
HellaMad

Reputation: 5374

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.

Upvotes: 3

Related Questions