Pure JavaScript fade in function

Based on this site

EDIT-1
Added the functionality so that user can specify the animation duration(@Marzian comment)

You can try this:

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

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

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

  tick();
}

var el = document.getElementById("div1");
fadeIn(el, 3000); //first argument is the element and second the animation duration in ms

DEMO

Leave a Comment