I just improved laaposto's answer to include a callback. I also added the fade_out function. It can be made more efficient, but it works great for what I'm doing.
Take a look at laaposto's answer for implementation instructions. You can replace JS in his violin with mine and see an example.
Thank Laaposto! This really helped for my project, which requires zero dependencies.
var el = document.getElementById( "div1" ); function fade_in( element, duration, callback = '' ) { element.style.opacity = 0; var last = +new Date(); var tick = function() { element.style.opacity = +element.style.opacity + ( new Date() - last ) / duration; last = +new Date(); if ( +element.style.opacity < 1 ) { ( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 ); } else { if( is_function( callback ) ) { callback(); } } }; tick(); } function fade_out( element, duration, callback = '' ) { element.style.opacity = 1; var last = +new Date(); var tick = function() { element.style.opacity = +element.style.opacity - ( new Date() - last ) / duration; last = +new Date(); if ( +element.style.opacity > 0 ) { ( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 ); } else { if( is_function( callback ) ) { callback(); } } }; tick(); } function is_function( object_to_check ) { return object_to_check && {}.toString.call( object_to_check ) === '[object Function]'; } fade_out( el, 3000, function(){ fade_in( el, 3000 ) } );
Hooray!
Justin waulters
source share