Javascript Style How to - Make a div fade out instead disappearing








Question

We would like to know how to make a div fade out instead disappearing.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){<!--   w  w  w  . j ava2s .  c o m-->
    function fade(element, duration) {
        var start = new Date;
        (function next() {
            var time = new Date - start;
            if(time < duration) {
                box.style.opacity = 1 - time / duration;
                requestAnimationFrame(next);
            } else {
                box.style.opacity = '0';
            }
        })();
    }
    document.getElementById("box").onclick = function() {
        fade(this, 2000);
    };
}
</script>
</head>
<body>
  <div id="box">Click here to fade</div>
</body>
</html>

The code above is rendered as follows: