micky.click
micky.click

Reputation: 11

Smooth way to replace background-image

I’m quite new to jQuery and JS and been asked to write a script that will be loading background-image progressively - I mean that low quality image should appear immediately and when full size image is loaded should replace the small one.

I found some tips how to do something similar by layering <img /> on top of background-image however in my case i have to deal with background-image only, so I have made this:

$('.img-loader').each(function(){
    var box = this;

    var smallImg = $(this).attr('style');
    var bigImg = smallImg.replace('.jpg)', 'big.jpg)');
    var imgUrl = bigImg.replace('background-image: url', '');
    var imgUrlS = imgUrl.replace(/[{()}]/g, '');
    console.log(imgUrlS);

    $('<img/>').attr('src', imgUrlS).load(function(){
        $(this).remove();
        $(box).attr('style', bigImg);
    });
})

The script basically does the job but in that moment when the image gets replaced there is a quite noticeable ‘shake’.

Any ideas how to make transition smoother or anyone knows what causing this 'shake'?

Edit: As suggested I'm adding a markup snipped of where script has to be applied.

<div class="about__section__bgimage img-loader"
style="background-image: url(<?php echo $contentBlock->imageurl ?>)"></div>

Upvotes: 1

Views: 120

Answers (2)

rubentd
rubentd

Reputation: 1275

I suggest you create two separate elements with the same size, overlapping each other, with position: absolute; make one of them visible with the original bg image (using opacity: 1). The second one invisible (using opacity:0)

Once the higher quality image is completely loaded, set the opacity of the original image to 0 and the new image to 1.

use a css transition on the opacity property to make the opacities change smoothly.

Upvotes: 3

Abdullah Khan
Abdullah Khan

Reputation: 645

you have to use animation for this. Use any of them according to your scenario enjoy it !!! https://daneden.github.io/animate.css/

Upvotes: 1

Related Questions