bigmadwolf
bigmadwolf

Reputation: 3519

How to animate a style property in plain vanilla javascript?

So for a while I've been moving away from jQuery, and in general just reducing my library use where-every possible to a) write leaner code, and b) really understand at a low level whats going on, particularly around the UI. While I've moved the majority of my UI animation to CSS3, theres often times when you need a little more control, but for a single tiny animation I'd prefer not to always have to pull in velocity.js or greensock etc.

Looking at you-might-not-need-jquery theres a fadeIn function they demostate that looks like this :

function fadeIn(el) {
  el.style.opacity = 0;

  var last = +new Date();
  var tick = function() {
    el.style.opacity = +el.style.opacity + (new Date() - last) / 400;
    last = +new Date();

    if (+el.style.opacity < 1) {
      (window.requestAnimationFrame && requestAnimationFrame(tick)) ||     setTimeout(tick, 16);
    }
  };

  tick();
}

fadeIn(el);

I generally understand this function, but have a few questions on very specific items :

  1. What does the + before new Date() and el.style.opacity on lines 3,5,6 & 8 indicate? is it something like += ?
  2. On line 5, why the division by 400?
  3. Is there anything inherently wrong with this recursive requestAnimationFrame technique for general quick animations?

If I understand the concept behind this pattern :

  1. we set our starting position (force feeding) and time we're beginning,
  2. we then update the style relevant to the amount of time thats passed,
  3. until the final state is satisfied, call tick again, on the next animation frame.

Is this correct?

Upvotes: 3

Views: 1046

Answers (1)

Pointy
Pointy

Reputation: 413757

  1. A unary + is a quick way to force a value to be interpreted as a number.
  2. The division by 400 is the way that code sets the rate of fade-in. A bigger number would make the fade take longer, and a smaller number would make it faster. The number gives the number of milliseconds that will elapse (more or less) before the element is fully opaque.
  3. It's not recursive. The reference to the function is passed to the timer mechanism (either setTimeout() or requestAnimationFrame()) but by the time the timer fires the original call will have exited.

Upvotes: 3

Related Questions