Created
November 1, 2016 16:42
-
-
Save sirtimid/e43d710827740e67f7140fb9f7f48c48 to your computer and use it in GitHub Desktop.
Fade in/out an element with vanilla javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Fade in/out an element | |
* Note: I am not using requestAnimationFrame as it does not play well in mobile browsers | |
* | |
* @param {Object} [options={}] An object with options. | |
* @param {Element} [options.el] The Element object. | |
* @param {String} [options.type='in'] The fade type: 'in' or 'out'. | |
* @param {Integer} [options.duration=400] The duration of the animation in miliseconds. | |
* @param {String} [options.display='block'] The display property of the element when fade in starts. | |
* @param {Boolean} [options.empty=false] Set to true if you need to empty the element after fade out. | |
*/ | |
function fade(options){ | |
options = Object.assign({ | |
type:'in', | |
duration:400, | |
display:'block' | |
}, options) | |
var isIn = options.type === 'in', | |
opacity = isIn ? 0 : 1, | |
interval = 50, | |
gap = interval / options.duration | |
if(isIn) { | |
options.el.style.display = options.display | |
options.el.style.opacity = opacity | |
} | |
var fading = window.setInterval(function() { | |
opacity = isIn ? opacity + gap : opacity - gap | |
options.el.style.opacity = opacity | |
if(opacity <= 0) options.el.style.display = 'none' | |
if(opacity <= 0 || opacity >= 1) { | |
if(fading) window.clearInterval(fading) | |
if(options.empty) options.el.textContent = '' | |
} | |
}, interval) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment