Adrian
Adrian

Reputation: 15

Change content of HTML element (div) for few seconds

I have a function which executes on click event from a button. After it clicked it displays me my message "Email was send!" in place of form.

After 5 seconds this message disappears and there is nothing left. How can I set the original content back to div after 5 seconds? Following is my snippet.

function myFunction() {
    document.getElementById("form").innerHTML = "Email was send!";
    setTimeout(function() {
        document.getElementById('form').style.display = 'none';
    }, 5000);
}

I want to display my message for 5 seconds then back to original form content.

Upvotes: 1

Views: 3343

Answers (4)

Lew
Lew

Reputation: 1278

You could save the innerHTML into a variable first and then set it back after. Here's what I mean:

function myFunction() {
  var form = document.getElementById("form")
  var originalContent = form.innerHTML
  form.innerHTML = "Email was sent"
  setTimeout(function() {
    form.innerHTML = originalContent
  }, 5000)
}

There's no need to set the display to none, this will hide the form completely.

Upvotes: 2

Jordi Flores
Jordi Flores

Reputation: 2150

<script>
function myFunction() {
        var originalContent = document.getElementById("form").innerHTML;
        document.getElementById("form").innerHTML = "Email was send!";
        setTimeout(function() {
                    document.getElementById('form').innerHTML = originalContent;
                 }, 5000);
     }
</script>

Upvotes: 0

Sean LeBlanc
Sean LeBlanc

Reputation: 586

To do what you're asking, you simply need to store the contents of the form before replacing it with the email message, then restore them in the timeout. Setting the form's display to none just hides the element without changing the contents.

e.g.

function myFunction() {
    var old_html = document.getElementById("form").innerHTML;
    document.getElementById("form").innerHTML = "Email was send!";
    setTimeout(function(){
        document.getElementById('form').innerHTML = old_html;
    }, 5000);
}

Although this should solve your problem, I would recommend putting the email message in a separate element and hiding/showing as necessary. It doesn't really make sense to replace the form contents if you're just going to put them back in five seconds later.

Upvotes: 2

Abhay
Abhay

Reputation: 413

Because you are setting display none of your form button.

Upvotes: 0

Related Questions