How to create a snackbar / toast with CSS and JavaScript?

CSSWeb DevelopmentFront End TechnologyJavascript

To create a snackbar/toast with CSS and JavaScript, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .snackText {
      visibility: hidden;
      min-width: 250px;
      margin-left: -125px;
      background-color: rgb(110, 26, 106);
      color: #fff;
      text-align: center;
      border-radius: 2px;
      padding: 16px;
      position: fixed;
      z-index: 1;
      left: 50%;
      bottom: 30px;
      font-size: 17px;
   }
   .snackBtn {
      border: none;
      padding: 10px;
      font-size: 18px;
      background-color: rgb(92, 0, 128);
      color: white;
   }
   .snackText.show {
      visibility: visible;
      animation: fadein 0.5s, fadeout 0.5s 2.5s;
   }
   @keyframes fadein {
      from {
         bottom: 0;
         opacity: 0;
      }
      to {
         bottom: 30px;
         opacity: 1;
      }
   }
   @keyframes fadeout {
      from {
         bottom: 30px;
         opacity: 1;
      }
      to {
         bottom: 0;
         opacity: 0;
      }
   }
</style>
</head>
<body>
<h1>Snackbar / Toast Example</h1>
<button class="snackBtn">Show Snackbar</button>
<h2>Click on the above button to see snackbar message</h2>
<div class="snackText">Some text some message..</div>
<script>
   document .querySelector(".snackBtn") .addEventListener("click", showSnackBar);
   function showSnackBar() {
      var x = document.querySelector(".snackText");
      x.className += " show";
      setTimeout(function() {
         x.className = x.className.replace("show", "");
      }, 3000);
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the “Show Snackbar” button −

raja
Published on 08-May-2020 16:12:28
Advertisements