Open In App

How to create a Snackbar using HTML, CSS & JavaScript?

Improve
Improve
Like Article
Like
Save
Share
Report

Snackbars in web design are notifications that are displayed on the website. Sometimes developers want to display additional notifications to the users, making them aware of certain information which is important but at the same time should not affect the user experience. This information can be about some kind of event that has occurred or will occur within the website, whether it was successful or not or that requires some quick user input or intervention.

Snackbars inform the users of processes that a website will perform or provide feedback on the processes that the website has already performed. For example, an unsuccessful API call, etc. They usually occur at the bottom of the screen within the website and should not hamper the current flow or user experience. They usually disappear on their own unless some user intervention is required. The Snackbars should only be displayed one at a time to avoid clogging the screen. They usually contain a single action such as Dismiss/Cancel/Ok and can be used as a part of the error handling as well. They can also be triggered by custom actions such as when the user clicks on a button.

Bootstrap and jQuery provide an extensive support for snackbar notification via classes and plugins but they can also be designed and implemented without any external libraries by simply using HTML, CSS, and JavaScript only. It is also important to know that many web frameworks such as Angular 4+, ReactJS, etc, and Android applications also provide support for Snackbar notifications and they can be implemented using their own classes and methods. For a detailed explanation, refer to the articles:

In this tutorial, we will implement Snackbar notifications for a website using HTML, CSS, and JavaScript only. We assume that you are familiar with HTML, and CSS rules and have a basic knowledge of CSS animations.

Approach:

Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML website, and CSS Animation and to load the respective JavaScript files. We will install Browsersync globally.

npm install -g browser-sync

Step 2: Create an “index.html” file, an index.css file, and an index.js in your project root folder.

  • HTML: Add the following code snippet in that file. 
  • CSS: By default, we have set the #snackbar HTML element to be hidden using the CSS visibility property. We have also defined the position: fixed; and z-index: 1; CSS properties for the Snackbar notification so that when it is made visible it will always be displayed above the screen for the User. Refer to the code comments for a better understanding. The !important CSS property states that all other conflicting rules on an HTML DOM element are to be ignored, and the rule denoted by !important is to be applied. This rule overrides all before-set CSS rules. We have used simple CSS animations to display the Snackbar notification to the users by fading into the screen and fading out of it. A detailed explanation of this can be found here. The total time set for the CSS animations depends upon the time limit for which we want the notification to be visible to the user. The time for the fadeout CSS Animation is calculated accordingly by subtracting 0.5 seconds from the total time in our case. 
  • JavaScript: We have used JavaScript to dynamically append a class to the HTML div element at the time when the Show Snackbar button is clicked. The showSnackbar() function is triggered by the onClick HTML Button property. The dynamically appended class, adds the CSS Rules to the #snackbar HTML element which makes it visible to the user. We have used the setTimeout() JavaScript function to dynamically remove the previously appended Class after 5 seconds, which will make the Snackar notification disappear. 

html




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>GeeksforGeeks</title>
    <!-- Loading External index.css file -->
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <h2>
     GeeksforGeeks - Snackbar using HTML, CSS & JS
    </h2>
  
    <!-- Custom Action to Trigger the Snackbar -->
    <button class="btn btn-lg" 
            onclick="showSnackbar()">
         Show Snackbar
    </button>
    <div id="snackbar">Hello GeeksforGeeks</div>
    <!-- Loading External index.js file -->
    <script src="index.js"></script>
</body>
</html>


CSS




#snackbar {
    /* By Default, Hidden */
    visibility: hidden
    min-width: 250px;
    background-color: #333;
    color: #fff;
    text-align: left;
    border-radius: 2px;
    padding: 16px;
    /* To always Keep on 
       Top of screen */
    position: fixed;
  
    /* To be displayed above 
       Parent HTML DOM element  */ 
    z-index: 1
  
    /* Position Bottom Left 
       Corner of Screen */
    left: 10px;
    bottom: 30px;
}
  
/* Dynamically Appending this 
   Class to #snackbar via JS */
.show-bar {
    visibility: visible !important;
    /* fadeout Time decided in 
       accordance to Total Time */
    /* In case, Time = 3s, 
       fadeout 0.5s 2.5s */
    animation: fadein 0.5s, fadeout 0.5s 4.5s;
}
  
/* when the Snackbar Appears */
@keyframes fadein {
    from {
        bottom: 0;
        opacity: 0;
    }
    to {
        bottom: 30px;
        opacity: 1;
    }
}
  
/* when the Snackbar Disappears
   from the Screen */
@keyframes fadeout {
    from {
        bottom: 30px;
        opacity: 1;
    }
    to {
        bottom: 0;
        opacity: 0;
    }
}


Javascript




function showSnackbar() {
    var snackBar = 
      document.getElementById("snackbar")
    // Dynamically Appending class
    // to HTML element 
    snackBar.className = "show-bar";
  
    setTimeout(function () {
       // Dynamically Removing the Class 
       // from HTML element
       // By Replacing it with an Empty
       // String after 5 seconds
       snackBar.className = 
          snackBar.className.replace("show-bar", ""); 
    }, 5000);
}


Step 3: We have successfully implemented Snackbar notifications using HTML, CSS, and JavaScript. In HTML, we have defined a custom Show Snackbar button which will trigger the Snackbar notification on the Screen. The Snackbar notification is a simple Text message which is displayed to the user. Since the Snackbar is a simple HTML “div” element, we can add custom actions to the Snackbar notification. For example, an “input box” or a “dismiss button”, if required. In our case, the snackbar notification will automatically disappear from the screen after 5 seconds. 

Output: 

Step 4: At this point our Snackbar Notification is ready. To launch the application using Browsersync, run the following command in the project directory or you can run the HTML file directly into your browser.

browser-sync start --server --files "*"

This starts Browsersync in server mode and watches all the files within the directory for changes as specified by the * wildcard. The application will be launched at http://localhost:3000/ by default. 

Output:

Snackbar Notification



Last Updated : 24 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads