How to Show a Div Element for Few Seconds in JavaScript

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.

You can check the working example online to verify the above code. The output will look like the following screenshot.

show div for 5 seconds in JavaScript

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.

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.

 

Latest articles

Related articles