How to create a Snackbar using HMTL, CSS & JavaScript? - GeeksforGeeks

15 Jul, 2020
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 which 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 with 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 the articles:
How to add a Snackbar in Android
How to create a SnackBar service?
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.
Step 1: Install Browsersync using npm. We will use Browsersync to start a server and provide a URL to view the HTML website, CSS Animation and to load the respective JavaScript files. We will install Browsersync globally.npm install -g browser-sync
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.index.html: Add the following code snippet in that file.htmlhtml<!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>index.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 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 which 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.csscss#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;    }}index.js: 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.JSJSfunction 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);}
index.html: Add the following code snippet in that file.htmlhtml<!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>
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>
index.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 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 which 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.csscss#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;    }}
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;    }}
index.js: 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.JSJSfunction 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);}
JS
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 being 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:
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:
JavaScript-Misc
Bootstrap
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?