I'm trying to make a fade in effect for new elements created with innerHTML
. This is part of a FullStack course, which only allows basic JS and CSS (no jQuery or other libraries). The particular exercise has you add notes to a parent element, but rather than displaying immediately, the notes are supposed to fade in (space is made for the note immediately, but it should be blank, showing just the background, and the note content should then fade in).
To implement this, I'm using CSS transitions. I create the new note element by appending to the parent element's innerHTML
property. Notes initially have an opacity of 0, which should create a hidden note. The fade-in is achieved with two pieces:
- a
transition
on the opacity property of notes, and - a 'fadeIn' class (added to new notes after creating them) that has an opacity of 1
After creating a new note, the 'fadeIn' class is added to the note, which should change the opacity from 0 to 1 and trigger the transition, causing a gradual fade-in. Instead, new notes show up immediately.
The following snippet shows how notes are created, how the 'fadeIn' class is added, and the CSS that should create a fade-in.
var tasksArray = [
{date: '2017-01-28', text: 'Work on FullStack course: CSS transitions exercise.', complete:true},
{date: '2017-01-29', text: 'Debug solution; figure out why new elements display immediately, rather than fading in.', complete:true},
{date: '2017-01-30', text: 'Ask for help on SO.', complete:true},
{date: '2017-01-31', text: 'Accept solution & upvote.', complete:false},
];
var notesArea = document.getElementById('Notes');
// code to focus on
function PrintNote(taskIndex) {
// Print a note for the given task.
notesArea.innerHTML +=
`<div id="taskN${taskIndex}">
<span class="noteTitle">Task #${taskIndex + 1}</span>
<p class="noteTXT">${tasksArray[taskIndex].text}</p>
<span class="noteDate">${tasksArray[taskIndex].date}</span>
</div>`;
// Get the new note.
noteDivsElement = document.querySelector("#taskN" + taskIndex);
// Change the new note's opacity by adding a class.
noteDivsElement.className = 'fadeIn';
}
// example only
function PrintNotes(i) {
PrintNote(i++);
if (i < tasksArray.length) {
setTimeout(() => PrintNotes(i), 1500);
}
}
PrintNotes(0);
div[id^="taskN"] {
/* styling to focus on */
opacity: 0;
transition: opacity 1s ease-in;
/* example only */
box-sizing: border-box;
margin: 4%;
border: 1px solid black;
padding: 0.5em;
background-color: #CCC;
width: 40%;
position: relative;
display: inline-block;
}
div[id^="taskN"].fadeIn{
/* styling to focus on */
opacity: 1;
}
<div id="Notes">
</div>
Why don't new notes fade-in, and how can I correct?