How to make text fade out

user4826496

I have an HTML form, and on a button click, javascript processes it, and text appears below the button, saying "form sent". I would like to make this text fade away after a few seconds, say around five. I am using this method to write the text in the first place:

document.getElementById('sent_box').innerHTML='form sent.';

The HTML box being written to looks like this:

<div id='sent_box'></div>

with this styling:

#sent_box{
height: 20px;
margin-top: 20px;
}

How would I be able to make the text fade out after ten seconds?

Note that I need a Vanilla Javascript solution to this. NO JQuery answers, please.

Thanks for any help!

Stewartside

You can do this with pure JS.

I've added comments for each line of the JS so you can understand and learn for future reference.

setTimeout(function() { // start a delay
  var fade = document.getElementById("fade"); // get required element
  fade.style.opacity = 1; // set opacity for the element to 1
  var timerId = setInterval(function() { // start interval loop
    var opacity = fade.style.opacity; // get current opacity
    if (opacity == 0) { // check if its 0 yet
      clearInterval(timerId); // if so, exit from interval loop
    } else {
      fade.style.opacity = opacity - 0.05; // else remove 0.05 from opacity
    }
  }, 100); // run every 0.1 second
}, 5000); // wait to run after 5 seconds
<div id="fade">Test</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related