If you want to add sleek, non-intrusive notifications (like success or error messages) to your web application, Toastr is a great choice. Toastr allows you to show messages such as success, error, or information in a compact and user-friendly format. In this blog, we will walk through how to set up Toastr in your web project, how to customize it, and how to use it to show different types of messages.

Step-by-Step Guide: Setting Up Toastr

1. Add the Toastr CSS and JS Files

First, you need to add Toastr's CSS and JavaScript files to your webpage. The easiest way to do this is by linking to the CDN (Content Delivery Network).

Add the Toastr CSS in the <head> section:

This will ensure that Toastr styles are applied to your notifications.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
Add the Toastr JS before the closing </body> tag:

This will make sure Toastr's JavaScript is loaded after your page content.

<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

Now, your basic HTML structure should look something like this:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Toastr Notification Example</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" />
    </head>
    <body>

        <!-- Your content here -->

        <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
    </body>
    </html>

2. Create a Custom Function to Show Toasts

Now that you have the necessary files, let's create a custom JavaScript function to show different types of notifications (success, error, info, etc.).

JavaScript Function for Toast Notifications:
function showToast(type, message, title = '') {
    // Toast options for customization
    const toastOptions = {
        positionClass: 'toast-top-right', // Position of the toast
        timeOut: 10000,                  // Duration of the toast (in ms)
        extendedTimeOut: 1000,           // Duration after mouse hover (in ms)
        width: '400px'                   // Toast width
    };

    // Show different types of messages based on the 'type' parameter
    if (type.toLowerCase() === 'success') {
        toastr.success(message, title, toastOptions);
    } else if (type.toLowerCase() === 'error') {
        toastr.error(message, title, toastOptions);
    } else if (type.toLowerCase() === 'info') {
        toastr.info(message, title, toastOptions);
    } else if (type.toLowerCase() === 'warning') {
        toastr.warning(message, title, toastOptions);
    }
}

3. Using the showToast Function

Now that you have the function to show toasts, you can use it anywhere on your page. Here's an example of how to display a toast message if a user does not fill out a form field (such as "Name").

Example Use Case: Checking an Empty Field

Let’s assume you have a form where the user is supposed to enter their name in a text input field (#txtName). If the user leaves it blank, we’ll show an error toast.

<form id="myForm">
    <label for="txtName">Name:</label>
    <input type="text" id="txtName" name="txtName">
    <button type="submit" id="submitButton">Submit</button>
</form>

<script>
    $("#submitButton").click(function(event) {
        // Prevent form submission to demonstrate the validation
        event.preventDefault();

        // Check if the 'txtName' input is empty
        if ($("#txtName").val() == "") {
            // Show error toast
            showToast("Error", "Please enter your name.", "");

            // Optionally, focus on the input field for better UX
            $("#txtName").focus();
        } else {
            // Handle form submission logic
            alert("Form submitted successfully!");
        }
    });
</script>
Explanation of Code:
  1. HTML Form: We have a basic form with an input field for the name (#txtName) and a submit button (#submitButton).

  2. JavaScript Validation:

    • When the user clicks the submit button, we check whether the txtName field is empty.

    • If the field is empty, we show an error toast using the showToast function we created earlier.

    • The toast will appear in the top-right corner with a message like "Please enter your name!".

  3. UX Enhancement: We use $("#txtName").focus(); to bring the user's attention back to the input field.

4. Customizing Your Toastr Messages

Toastr is highly customizable. You can change the toast’s appearance, behavior, and position by modifying the options object inside the showToast function.

Some additional options you can tweak are:

  • positionClass: Controls where the toast appears on the screen (toast-top-left, toast-top-right, toast-bottom-right, etc.).

  • timeOut: The duration (in milliseconds) for which the toast remains visible. Default is 5000ms (5 seconds).

  • extendedTimeOut: The duration for which the toast stays visible after the user hovers over it.

  • closeButton: Add a close button to allow the user to dismiss the toast manually.

Conclusion

Using Toastr to show success, error, or informational messages in your web application is straightforward and effective. By following the steps above, you can easily integrate Toastr notifications into your app and provide a better user experience.

Remember:

  • Toastr CSS should be added in the <head> section of your page.

  • Toastr JS should be added just before the closing </body> tag.

  • Use the showToast() function to handle different types of notifications and customize them to suit your needs.

Now, you can add beautiful and user-friendly notifications to your web application without much hassle!

Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions