How can i auto-hide the message "You have been subscribed to our newsletter " after sometime?

Viewed 59

The message "You have subscribed to our newsletter" is not auto-hiding itself, i have to refresh the page every time i need to enter a new entry in page and also i want the form area to be blank .see in the below image i want to hide that subscription message after sometime on its own and email area should also be blank to get a new entry.

 <script type="text/javascript">
function doSubscribe() {
    var subscriberEmail = document.getElementById("subscriberEmail").value;
     
    var ajax = new XMLHttpRequest();
    ajax.open("POST", "subscribe-newsletter.php", true);
    ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
     
    ajax.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
           
        }
        
    };

    ajax.send("subscriberEmail=" + subscriberEmail);
    return false;
}

what should do so the message autohides itself without refreshing the page and the email area should also be blank.

2 Answers

You need a small change in your onreadystatechange function:

NOW

if (this.readyState == 4 && this.status == 200) {
      document.getElementById("subscribe-message").innerHTML = "You have been subscribed to our newsletter.";
}

MOST BE

if (this.readyState == 4 && this.status == 200) {
    var element = document.getElementById("subscribe-message");
    element.innerHTML = "You have been subscribed to our newsletter.";
    setTimeout(() => {
        element.innerHTML = "";
    }, 3000) // Put your delay in milliseconds ex: 3 seconds is 3000 milliseconds
}

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. The function is only executed once.

You can handle that with setTimeout (this example has 2.5 seconds delay), you can set the innerHTML as an empty string, or hide, or remove from DOM, try this:

let elem = document.getElementById("subscribe-message");

function showMessage(){
    elem.innerHTML = "You have been subscribed to our newsletter.";
    setTimeout(() => {
        elem.innerHTML = '';
        //elem.style.display = 'none'; (hides)
        //elem.remove(); (remove element from DOM)
    }, 2500)
}

showMessage();
<p id="subscribe-message"></p>

Related