Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery animate transform translate x,y

Tags:

jquery

I need to animate an image, but I would like to use CSS transforms. I found a previous question where the solution was this:

jsFiddle

I modify it this way:

jsFiddle

I don't know how to pass x and y values, since I need to translate(x,y) both.

This way doesn't work:

$('#box').animate({  fake: [100,50] }, {
    step: function(now,fx) {
       $(this).css('-webkit-transform','translate(' + now[0] + 'px,' + now[1] + 'px)'); 
    },
    duration:'slow'
},'linear');

2 Answers

;(function($) {
            var delay = 0;
            $.fn.translate3d = function(translations, speed, easing, complete) {
                var opt = $.speed(speed, easing, complete);
                opt.easing = opt.easing || 'ease';
                translations = $.extend({x: 0, y: 0, z: 0}, translations);

                return this.each(function() {
                    var $this = $(this);

                    $this.css({ 
                        transitionDuration: opt.duration + 'ms',
                        transitionTimingFunction: opt.easing,
                        transform: 'translate3d(' + translations.x + 'px, ' + translations.y + 'px, ' + translations.z + 'px)'
                    });

                    setTimeout(function() { 
                        $this.css({ 
                            transitionDuration: '0s', 
                            transitionTimingFunction: 'ease'
                        });

                        opt.complete();
                    }, opt.duration + (delay || 0));
                });
            };
        })(jQuery);

In this way you can use also translateZ;

source http://cameronspear.com/blog/animating-translate3d-with-jquery/

like image 99
Giovanni Brescia Avatar answered May 12 '26 11:05

Giovanni Brescia


$('#box').animate({  fake: 200, fake2: 10 }, {
    step: function(now,fx) {
      $(this).css('-webkit-transform','translate('+now+'px,'+now+'px )'); 
    },
    duration:'slow'
},'linear');

jsFiddle

like image 26
Ahmad Santarissy Avatar answered May 12 '26 13:05

Ahmad Santarissy