Question

I have a fiddle here: jsfiddle.net/VnGRL/

In the fiddle, on update() it changes the CSS of .scroll to artificially scroll the whole element. This works fine:

$('.scroll').css({ 
    "transform": "translate3d(0, -" + newHeight + "px, 0)",
    "-webkit-transform": "translate3d(0, -" + newHeight + "px, 0)"
});

However as soon as I use .animate() nothing happens:

$('.scroll').animate({ 
    "transform": "translate3d(0, -" + newHeight + "px, 0)",
    "-webkit-transform": "translate3d(0, -" + newHeight + "px, 0)"
}, 800);

There's a similar question here but it's just where they didn't include px

Was it helpful?

Solution

I suggest you to use CSS animation, it should always be available if translate3d is available.

$('.scroll').css({
  '-webkit-transition-duration': '350ms',
  'transition-duration', '350ms'
});

Actually, your code can't work because animate is a powerful like basic function. It will take what you gave as property, and try to tend to this value, but you gave some weird value which is not a number, but rather a string containing some numbers translate3d(x,y,z), jQuery doesn't know how to handle that.

If you really need to do it in JavaScript (to have the final callback for instance), I suggest you can use the following method. I made it really simple, if it's critical, it could be better to improve it with jQuery FX and the effect stack.

var animateTranslate3d(el, values, duration, complete, oldValues) {
  var $el = $(el),
      stepDuration = 10,
      remainingSteps = Math.floor(duration / stepDuration),
      newValues;

  // Optimization, after the first step, oldValues never needs to be computed again
  oldValues || (oldValues = ($el.css('transform') || $el.css('webkit-transform') || 'translate3d(0,0,0)').match(/translate3d\((\d).*,(\d).*,(\d).*\)/)).shift();
  newValues = [(values[0] - oldValues[0]) / remainingSteps, (values[1] - oldValues[1]) / remainingSteps, (values[2] - oldValues[2]) / remainingSteps];

  $el.css('transform', 'translate3d(' + newValues[0] + ',' + newValues[1] + ',' + newValues[2] + ')');

  // Animation finished
  if(duration <= 0) return (typeof complete === 'function' && complete());

  // Let's do the next step after a stepDuration delay
  setTimeout(function(){animateTranslate3d(el, values, duration - stepDuration, complete, newValues)}, stepDuration)
}

animateTranslate3d('.scroll', [0, -newHeight, 0], 800);

Tell me if it works correctly ;), maybe you will need to debug it a little...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top