/ Published in: JavaScript
Smoothness of fade out animation needs work
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Set the opacity CSS for required element */ function setOpacity(elem,level) { //if filters then IE //use alpha opacity if (elem.filters) { elem.style.filter = 'alpha(opacity=' + level + ')'; } else { //else use W3C opacity CSS elem.style.opacity = level / 100; } } /** * Fade out the required element over time using CSS */ function fadeOut(elem) { //20 frame animation for ( var i = 0; i < 100; i += 5 ) { //anonymous closure makes sure correct i is used //for each iteration (function(){ //opacity is i var opacity = i; //animation setTimeout(function(){ // Set the new opacity of the element setOpacity( elem, 100 - opacity ); //completely hide the element at 95% if ( opacity == 95 ) elem.style.display = 'none'; //for smooth animation change the timeout delay //proportionately with opacity }, ( i + 1 ) * 10 ); })(); } } //get id of element that closes element var myElm = document.getElementById('myElement'); //close the element on click myElm.onclick = function() { fadeOut(document.getElementById('fadeOutElement')); };