How to Hide an Alert Message After a Specific Time (5 seconds) using JavaScript?

Hide alert message automatically after some time is a great feature to make web form UI user-friendly. With the auto-hide feature, the alert message element closes automatically after some specific time and disappears from the web page. In this example code, we will show you how to hide an alert message after 5 seconds using JavaScript.

HTML element to be hidden:
Here the alert message element which will disappear after some time of display on the webpage.

<div class="alert">
    A simple alert message!
</div>

Hide HTML element after specific time using JavaScript:
Use the setTimeout() method to create a timer with a specific time (delay time in milliseconds), which executes code after 5 seconds once the time expires.

  • The Document:querySelector() is used to select the HTML element of the alert message by class name.
setTimeout(function() {
    document.querySelector('.alert').remove();
}, 5000);

Leave a reply

keyboard_double_arrow_up