Displaying Toast Messages with Tailwind CSS

Updated: December 7, 2023 By: Khue Post a comment

The complete example below shows you how to create a toast, a kind of alert message that mimics the push notifications that have been popularized on mobile applications. A typical toast usually contains a brief message and will automatically disappear after appearing for a few seconds. We make it by using Tailwind CSS and a little vanilla Javascript (just a few lines of this programming language).

Table Of Contents

Preview

Our sample webpage has a button. When this button gets clicked, a toast will show up in the bottom right corner. It will stay there for 5 seconds and then go away automatically.

The code

The complete code with explanations in the comments:

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Sling Academy</title>
</head>

<body class="bg-amber-100 px-20 py-10">
    <h3 class="mt-4 text-3xl">Toast Example</h3>

    <!-- This button is used to call the showToast() function -->
    <div class="mt-10 space-x-5">
        <button onclick="showToast()" class="px-6 py-3 bg-blue-500 hover:bg-blue-600 text-white">Show Toast</button>
    </div>

    <!-- Implement the toast -->
    <div id="myToast"
        class="hidden fixed right-10 bottom-10 px-5 py-4 border-r-8 border-blue-500 bg-white drop-shadow-lg">
        <p class="text-sm">
            <!-- Polish the toast with an circle blue "i" (stands for information) -->
            <span class="mr-2 inline-block px-3 py-1 rounded-full bg-blue-500 text-white font-extrabold">i</span>
            This is a toast. Welcome to SlingAcademy.com
        </p>
    </div>

    <!-- Javascript code -->
    <script>
        function showToast() {
            // Show the toast
            document.getElementById("myToast").classList.remove("hidden");
            // Hide the toast after 5 seconds (5000ms)
            // you can set a shorter/longer time by replacing "5000" with another number
            setTimeout(function () {
                document.getElementById("myToast").classList.add("hidden");
            }, 5000);
        }

    </script>
</body>

</html>

That’s it. Happy coding and have fun with Tailwind CSS.