MANICX100
MANICX100

Reputation: 1369

jQuery background image change on timer

I have a div:

<div class="coverImage" style="background-image:url('3.2.5\\assets\\img\\backgroundCanvas1.jpg');"></div>

and an attached jQuery script to rotate its background every 20 seconds

var coverChange =
{
    init: function()
    {

        var itemInterval = 20000;

        var numberOfItems = 4;

        var currentItem = 1;

        $('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");

        //loop through the items
        var infiniteLoop = setInterval(function(){
            $('.coverImage').attr("style", "background-image:url()");

            if(currentItem == numberOfItems -1){
                currentItem = 1;
            }else{
                currentItem++;
            }
            $('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");

        }, itemInterval);
    }
};

coverChange.init();

When the image changes it happens to white out the bottom half until I scroll slightly. My main ask is help with a fadeIn of the new image. (everything else is secondary)

I have experimented using the jQuery fadeIn property but cannot get it to work in a seamless aesthetically pleasing way.

I am not looking for code elegance only function, as you can tell :-)

P.S Loading the image initially via CSS did not work.

Upvotes: 0

Views: 852

Answers (2)

mark_c
mark_c

Reputation: 1212

You should be able to add a simple CSS transition to your coverImage element.

.coverImage {
    transition: background 1s;
}

I've created a working example at https://jsfiddle.net/mark_c/pa44n42k/1/

Upvotes: 1

The SuperKat
The SuperKat

Reputation: 234

For a fade in out effect, you should simply fade out the div before this step:

$('.coverImage').attr("style", "background-image:url()");

and fade it in after this step:

$('.coverImage').attr("style", "background-image:url('3.2.5/assets/img/backgroundCanvas"+currentItem+".jpg'");

For fade in out you can use simple jquery as I suppose you already have but not the right way, so good luck.

This will give you a nice fade in/out effect. :)

Upvotes: 0

Related Questions