JQuery: Display an element for 5 seconds.

This is a short guide on how to display a UI message (or any element, for that matter) for 5 seconds using JavaScript. For this tutorial, we will be using the popular JavaScript library JQuery to:

  1. Fade a div in and display it.
  2. Fade it back out again after 5 seconds (hide it).

Let’s take a look at the following example:

<html>
    <head>
        <meta charset="UTF-8">
        <title>Show Message For Five Seconds</title>
    </head>
    <body>
        <!--Our div is hidden by default-->
        <div id="message" style="display:none;">Hello!</div>
        
        <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script>
        //When the page has loaded.
        $( document ).ready(function(){
            $('#message').fadeIn('slow', function(){
               $('#message').delay(5000).fadeOut(); 
            });
        });
        </script>
    </body>
</html>

If you run the example above, you’ll see that the message “Hello!” is displayed in the browser for five seconds before it is faded out and hidden from the user. A quick explanation of the code above:

  • We gave our div the id “message” – this allows us to easily access it via JQuery.
  • We gave our an inline style of “display:none” – this makes sure that the div and the text inside it is hidden by default.
  • We included the JQuery library file from the JQuery CDN.
  • We used the ready function in order to make sure that our code does not execute until the page has been loaded.
  • Once the page is loaded, we display the div by using the fadeIn function.
  • When the message is faded in, we use the delay function to delay the execution of fadeOut by 5 seconds. Note that the “5000” figure that we passed to the delay function is 5 seconds in milliseconds. i.e. If you want it be displayed for 3 seconds, then you can use “3000” instead of “5000”. If you want the element to be displayed for 10 seconds, then you will need to use “10000”.

This kind of functionality can come in handy whenever you want to temporarily display notifications or errors to the user.