Fadeout DOM element


/ Published in: JavaScript
Save to your folder(s)

Smoothness of fade out animation needs work


Copy this code and paste it in your HTML
  1. /**
  2.  * Set the opacity CSS for required element
  3.  */
  4. function setOpacity(elem,level) {
  5. //if filters then IE
  6. //use alpha opacity
  7. if (elem.filters) {
  8. elem.style.filter = 'alpha(opacity=' + level + ')';
  9. } else {
  10. //else use W3C opacity CSS
  11. elem.style.opacity = level / 100;
  12. }
  13. }
  14.  
  15. /**
  16. * Fade out the required element over time using CSS
  17. */
  18. function fadeOut(elem) {
  19. //20 frame animation
  20. for ( var i = 0; i < 100; i += 5 ) {
  21. //anonymous closure makes sure correct i is used
  22. //for each iteration
  23. (function(){
  24. //opacity is i
  25. var opacity = i;
  26. //animation
  27. setTimeout(function(){
  28. // Set the new opacity of the element
  29. setOpacity( elem, 100 - opacity );
  30. //completely hide the element at 95%
  31. if ( opacity == 95 )
  32. elem.style.display = 'none';
  33. //for smooth animation change the timeout delay
  34. //proportionately with opacity
  35. }, ( i + 1 ) * 10 );
  36.  
  37. })();
  38. }
  39. }
  40.  
  41. //get id of element that closes element
  42. var myElm = document.getElementById('myElement');
  43.  
  44. //close the element on click
  45. myElm.onclick = function() {
  46. fadeOut(document.getElementById('fadeOutElement'));
  47. };

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.