Search code examples
javascriptjqueryhtmlcssfading

Fading a dynamically changed (jQuery) background image?


I have a block on a website I am working on which consists of some buttons and a background image.

I need to change the background image every 3 seconds so I have the following javascript :

jQuery('.myBlock').css({"background-image" : "url(img1)"});

var counter = 0;
function setBckImage(){
    if(counter<3){
        counter++;
    } else {
        counter=1;
    }

    switch (counter){
        case 1:
            jQuery('.myBlock').css({"background-image" : "url(img1)"});
            break;
        case 2:
            jQuery('.myBlock').css({"background-image" : "url(img2)"});
            break;
        case 3:
            jQuery('.myBlock').css({"background-image" : "url(img3)"});
            break;
    }
}

setInterval(setBckImage, 3000);

Which works, but the change is "sudden" and I would like it to be more smooth, adding a fadein/fadeout effect. How can I achieve this ? I saw this answer that lead to this link but in this link, the images are inside div, they are not backgroud-image, so I don't understand how to adapt this answer to my code.

Is there a way to achieve this ?


Solution

  • Probably you want that effect?

    $('.myBlock').css({"background-image" : "url(http://nakolenke.club/uploads/posts/2016-09/1473248821_kotiki04.jpg)"});
    
    var counter = 0;
    function setBckImage(){
        if(counter<3){
            counter++;
        } else {
            counter=1;
        }
    
        switch (counter){
            case 1:
                jQuery('.myBlock').css({"background-image" : "url(http://nakolenke.club/uploads/posts/2016-09/1473248821_kotiki04.jpg)"});
                break;
            case 2:
                jQuery('.myBlock').css({"background-image" : "url(http://nakolenke.club/uploads/posts/2016-09/1473248821_kotiki04.jpg)"});
                break;
            case 3:
                jQuery('.myBlock').css({"background-image" : "url(http://i.bigmir.net/img/dnevnik/uploads/cmu_1153/29306/1.jpg)"});
                break;
        }
    }
    
    setInterval(setBckImage, 3000);
    .myBlock {
      width: 100px;
      height: 100px;
      background-size: cover;
       -webkit-transition: background 700ms ease-in 700ms;
        -moz-transition: background 700ms ease-in 700ms;
        -o-transition: background 700ms ease-in 700ms;
        transition: background 700ms ease-in 700ms;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="myBlock"></div>