Updating css class when div content is posted on the fly

Hi,
OK, so my CSS, relevant HTML and JS will follow but first, here’s the explanation.

In my webpage, when the user submits a form of textarea content, an ajax insertion is fired off to put the submitted data into the Db. Then, the specific DIV is populated with the success message.

That all works but what I also need is a time-delay to remove the ‘success message’ after say 5 seconds and also, to remove it gradually/smoothly. Currently, it removes suddenly, after about 10 seconds. No smoothness. no ease-in ease-out smoothness.

Why does it seem that the visibility (duration) of the message seems to match the sum of transition-duration and transition-delay?
What way should I change it so the message disappears smoothly after 5 seconds?

The CSS:

     <style>
     #viewing-notes-saved-message{
         color: green;
         text-align:left;
         transition-property: visibility, font-size, color;
         transition-timing-function: ease-in-out;
         transition-duration: 5s;
         transition-delay: 5s;
     }
    </style> 

The HTML

<div id='viewing-notes-saved-message'></div>

The JS

$("#viewing-notes-saved-message")
  .text('That viewing comment has been saved'); 
document.getElementById("viewing-notes-saved-message")
  .style.visibility = "hidden";

You can’t do a transition on visibility as it is either on or off. You will need to transition on opacity as well.

HTML:

<div id='viewing-notes-saved-message'></div>

CSS:

#viewing-notes-saved-message {
  transition: visibility 1s linear, 
  opacity 1s linear;
} 

.hide {
  opacity: 0;
  visibility: hidden; 
}

JS:

window.addEventListener('DOMContentLoaded', () => {
  const messageElem = document.querySelector('#viewing-notes-saved-message');
  messageElem.textContent = 'That viewing comment has been saved';
  setTimeout(() => messageElem.classList.add('hide'), 5000)
})

You maybe able to achieve this with CSS animation, but here I have used Javascript. The text is added and then a setTimeout is used to add a hide class to the element after 5000ms (5s).

2 Likes

Thanks RPG_Digital. I’ll study that because it still cuts the display (of that message) suddenly. I’ll look for any potential conflicts with other CSS though using opacity seems to do it. (On chrome at least).
CSS

 #viewing-notes-saved-message{
 line-height: 1em;
 color: green;
 text-align:left;
 transition-property: color, text, opacity, visibility, font-size;
 transition-timing-function: ease-in-out;
 transition-duration: 3s;
 transition-delay: 2s;
 }

HTML

<div id='viewing-notes-saved-message'></div>

JS:

$("#viewing-notes-saved-message").text('That viewing comment has been saved'); 
document.getElementById("viewing-notes-saved-message").style.opacity = 0;