I’m looking to create a smooth fade effect for the content inside a block that is being dynamically changed by script. Instead of an instant change, I want the old content to fade out and the new content to fade in gradually without using jQuery — just pure JS and CSS. Here’s what I’ve tried: I defined two classes in CSS, one with transparency and one without, each with a transition set to 2 seconds. My plan was to toggle these classes when the content changes, expecting a smooth fade-out and fade-in effect. However, the content simply changes instantly. CSS:
.non-opaque {
opacity:0;
transition: opacity 2s linear;
}
.opaque {
opacity:1;
transition: opacity 2s linear;
}
HTML
<div class="alert alert-info" id="wrapper">
<p id="text-box">…</p>
</div>
JS
var textBox = document.getElementById('text-box');
window.onload = function () {
var failCounter = 0;
var current = notes[Math.floor(Math.random() * 12)];
textBox.className = 'opaque';
textBox.innerHTML = '…';
function keyClicked(event) {
if (event.target.className.split(' ')[1] === current) {
textBox.className = 'non-opaque';
textBox.innerHTML = '*some altered content*';
textBox.className = 'opaque';
…
In my JavaScript code, I initially set the content wrapper block to the 'opaque' class with the initial content. Then, under certain conditions, I switch it to 'non-opaque', update the innerHTML with the relevant content, and finally revert back to 'opaque'. Despite this approach, no animation takes place. What am I doing wrong?