0

I am adding css background to multiple divs and I want to do it in a row and one after another. Now that I add css to all divs, it adds all the background-images to all divs at once which makes the images to load slowly.

this is my jquery code :

$('#m-portfolio .slick-slide').each(function(){
    var $item   = $(this),
        img     = $item.find('.m-p-view').attr('data-lazyload'),
        bg      = $item.find('.m-p-view').attr('data-bg');

    $item.find('div.slice').css('background-image', 'url(' + img + ')');
    $item.find('.m-p-view').css('background-image', 'url(' + bg + ')');    
});

1 Answer 1

1
$(function () {
    $('#m-portfolio .slick-slide').each(function (i, item) {
        var $item = $(this).hide(),
            $mpview = $item.find('.m-p-view'),
            $slice = $item.find('.slice'),
            img = $mpview.attr('data-lazyload'),
            bg = $mpview.attr('data-bg');
        $('<img src="' + img + '" />').load(function () {
            $slice.css('background-image', 'url(' + img + ')');
            $('<img src="' + bg + '" />').load(function () {
                $mpview.css('background-image', 'url(' + bg + ')').parent('.slick-slide').delay(i + '000').fadeIn();
            });
        });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

what is div slice? Is a preview Image before the bigger one load? Not Exactly. Both of them are div backgrounds. One div is upper than another. When I click on the upper, it folds like a paper and the lower background shows up. Now, the problem is something else. I have got for example 10 elements like this with the same classes and because of that I used each and I dont want them to load at once together
Thanks. Not exactly, but this is somehow what I need. I am going to work on it
@Afshin Haghighat : with load() function you will sure that image is fully loaded before it display, so no flickering image will appear. then if you pre-set the .m-p-view to hidden, with the help of fadeIn() function you can make it display one after another at specified time using the i to increment each single item. This is because rendering of images is even faster then you can think, for this reason also if you load() all the images you will not see a real one-by-one effect that for istance you can achieve with fading effect.
@Afshin Haghighat i have updated the code tu suit your need, try it and let me know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.