WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

CSS: Avoid image hover first time blinking / flicker

If you’ve ever used image replacement on hover for your background images then you will have noticed this annoying ‘blinking/flicker’ the first time you hover over the element. That’s because we are not pre-loading the image and so I would recommend loading the image on load to avoid this.

Here is a simple and effective CSS image preloading technique I have used several times. You can load several images by placing content: url() url() url()… etc.


body:after {
    display: none;
    content: url(path/to/image-hovered.jpg) url(path/to/another-image-hovered.jpg);
}

This can be done in various other ways but the CSS method is my preferred method.

If you want to go ahead and use a JavaScript method you can use the code below:-


function preloader() {
	if (document.images) {
		var img1 = new Image();
		var img2 = new Image();
		var img3 = new Image();

		img1.src = "http://domain.com/path/to/image-001.gif";
		img2.src = "http://domain.com/path/to/image-002.gif";
		img3.src = "http://domain.com/path/to/image-003.gif";
	}
}
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}
addLoadEvent(preloader);

I hope this helps!

If you want to see this in action, have a look at this CodePen we created here.

 

Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

4 thoughts on “CSS: Avoid image hover first time blinking / flicker

  1. Ola Silva!
    Muito bom o seu blogg.
    Somente uma sugestão!

    Voce poderia criar seus exemplos no CODEPEN https://codepen.io/ e depois linkar em suas materias, assim poderiamos visualizar melhor ..

    Obrigado.

    //Paulo

Join the discussion