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.
setTimeout(function() {
document.querySelector('.alert').remove();
}, 5000);