In web development, there are situations where you want to show div elements for a few seconds just to notify the user about an action. This can be achieved with JavaScript very easily.
How to Display A Div for a Few Seconds
A simple way to display a div for a few seconds is to hide a div element by default and then show it on the screen. For this, you need to set the default style display:none
for the div element. The following example displays the notification div for 5 seconds after the button is clicked.
1 2 3 4 5 6 7 8 |
<div id="notification" style="display:none;"> <p>You clicked the button. Wait for 5 seconds now. </p> </div> <button id="button">Click Me to Display </button> |
1 2 3 4 5 6 7 8 9 10 |
const notification = document.querySelector("#notification"); const button = document.querySelector("#button"); button.addEventListener("click", ()=>{ notification.style.display = "block"; setTimeout(()=>{notification.style.display="none"},5000); }); |
You can check the working example online to verify the above code. The output will look like the following screenshot.
Toggling a Class to Show Div for 5 Seconds in JavaScript
As you might know, adding inline styles is not a good practice when you are working on a scalable project. So, the better way to show a div for a few seconds is to toggle a CSS class on a button click. The following example toggles a CSS class to show a div for 5 seconds.
1 2 3 4 5 6 7 8 |
<div id="notification" class="hide-notification"> <p>You clicked the button. Wait for 5 seconds now. </p> </div> <button id="button">Click Me to Display </button> |
1 2 3 4 5 6 7 |
.hide-notification{ display:none; } |
1 2 3 4 5 6 7 8 9 10 |
const notification = document.querySelector("#notification"); const button = document.querySelector("#button"); button.addEventListener("click", ()=>{ notification.classList.remove("hide-notification"); setTimeout(()=>{notification.classList.add("hide-notification");},5000); }); |
Conclusion
There are 2 ways to show a div element for [n] number of seconds with JavaScript. The first method is to add a style to hide the div and then change the styles to show it for a few seconds. The second method is to toggle a class on a button click with JavaScript. The examples above use setTimeout
function that you can read on mozilla documentation.