Dan Jay
Dan Jay

Reputation: 873

JQuery image slider and CSS transition works only once

I'm trying to learn jQuery plugins. I'm creating a image sliding plugin. This is how I've developed so far.

(function($){

        $.imageSlider = function(selector, settings) {

        //settings

        var config = {      
            'delay':2000,
            'speed':500
        };

        if(settings) {
            $.extend(config, settings);
        }

        //vars
        var obj = $(selector);

        obj.children('img').css('transition','width 2s, height 2s, transform 2s');      
        var image = obj.children('img');
        var count = image.length;

        var i = 0;

        image.eq(0).show(); //first image showing

        //begin the image loop

        setInterval ( function() {
                image.eq(i).fadeOut(config.speed);
                i = (i+1 == count) ? 0 : i+1;
                image.eq(i).fadeIn(config.speed);
                image.eq(i).css("transform","rotate(360deg)");
            }, config.delay
        );

        return this;
    }

})(jQuery);

But my the issue is the rotation happens only once cycle.

JSFiddle http://jsfiddle.net/va45D/1/

After all 3 images loaded as the way I wanted, then It doesn't applies the transition.

Please help me to understand whats happening here.

Upvotes: 1

Views: 650

Answers (1)

Eliezer Bernart
Eliezer Bernart

Reputation: 2426

Hie Shan,

I can reproduce your problem, you're right. After the second time that you rotate your images they will not rotate anymore. I'm using Firefox 25.

To solve you problem I made these updates:

setInterval( function() {
        image.eq(i).fadeOut(config.speed);    
        image.eq(i).css("transform","rotate(0deg)");
        i = (i+1 == count) ? 0 : i+1;
        image.eq(i).fadeIn(config.speed);
        image.eq(i).css("transform","rotate(360deg)");
    }, config.delay
);

When your loop over, the element keeps the same value at the end of the loop, so when your run it for the first time your have all your img elements at 0deg, at the end you transform them to 360deg position. The next time that you run your loop (this explain the problem that you have on your 2nd time), all your images starts on 360deg. If you rotate 360deg to 360deg you have the same position because there is no interval between the actual position and the new one. This can be really visible if you update your code to 45deg, as you can see on this fiddle.

Before start the process I defined a transformation that returns your element to 0 degrees. Maybe this solution solves your problem.

Here is the JSFiddle

Thanks!

Upvotes: 4

Related Questions