Try not to worry about fading in/out the innerHTML
property. Instead, wrap the innerHTML in a span
tag (or, alternatively, a div
tag), and then simply fade that element in and out.
Here it is with a 1,000 millisecond delay:
const fadetime = 1000;function fadeInElement(element) { element.style.removeProperty('display'); setTimeout(function() { element.classList.remove('fade'); }, 10); return true;}function fadeOutElement(element) { element.classList.add('fade'); setTimeout(function() { element.style.display = 'none'; }, fadetime); return true;}var buttondisplay = false;document.getElementById('button').addEventListener('click', function(ev) { if(buttondisplay) { fadeOutElement(document.getElementById('button-text-2')); setTimeout(function() { fadeInElement(document.getElementById('button-text-1')); }, fadetime); } else { fadeOutElement(document.getElementById('button-text-1')); setTimeout(function() { fadeInElement(document.getElementById('button-text-2')); }, fadetime); } buttondisplay = !buttondisplay;});
.fadeable { opacity: 1; transition: opacity 1s;}.fade { opacity: 0 !important;}
<button id="button"><span id="button-text-1" class="fadeable">First Text</span><span id="button-text-2" class="fadeable fade" style="display:none;">Second text!</span></button>