How to create Toast or Snackbar using CSS and JavaScript

Nitish Kumar Singh

Nov 10, 2023 . 4 min read

Hello Developers! In this blog post, we will create a Toast or Snackbar using CSS and JavaScript to show a short-duration, non-interactive message to the user upon an action. We will design the Toast to be versatile, serving as an informational, warning, error, or success message by utilizing different colors for each message type. Additionally, we'll explore the customization of the Toast's position on the screen.

What is Toast or Snackbar?

A Toast, Snackbar, or similar component is a non-interactive UI element used to display a message to the user for a short time span. Components like these are employed to show brief messages or notifications without requiring user interaction. They appear on the screen with an animation, delivering a concise message, and automatically dismiss after a short period without any user interaction. Typically, we use them to convey messages in the following scenarios:

  • Form Submission Success/Failure: After a user submits a form, we can display a Snackbar to confirm success or inform about an error.
  • User Authentication: To confirm successful login or notify about authentication errors.
  • Data Updates: When data is successfully updated or if there's an issue during the update process.
  • Alerts or Warnings: For non-critical warnings or alerts that don't require a full page refresh.
  • Network Actions: When performing actions that require an internet connection, like syncing data or sending a message.
  • Product Added to Cart: In e-commerce websites, showing a Snackbar when a user adds a product to their cart.

Above are common use cases where we use components like this, but they can be employed in many more situations. It completely depends on the use case where and how to use them.

So, without any more theoretical introduction, let's start building. Add the following CSS to your CSS file:

.toast {
  position: fixed;
  margin: 10px;
  border-radius: 5px;
  color: white;
  padding: 10px;
  font-size: 15px;
  letter-spacing: 0.4px;
  font-family: sans-serif;
}

Customize above CSS as your requirements, like margin, font styling and boder-radius but keep position fixed because you change it then you need to change over all JavaScript code.

Add following JavaScript to a JS file:

const types = { info: "dodgerblue", warn: "darkorange", error: "red",success:"forestgreen" };
export const showToast = (o)=> {
  if (!o) o = {message:"Empty message"}
  const { message, time, from, type } = o;

  const m = document.createElement("div"); m.classList.add("toast");
  const keyframes = [];
  let s = "";
  switch (from) {
    case "tl": case "tr":
      keyframes.push({ transform: "translateY(-100%)", top: 0 });
      s = from === "tl" ? "let:0;top:0;" : "right:0;top:0;"; break;
    case "bc":
      keyframes.push({ transform: "translateY(100%)", bottom: 0 });
      s = "right:10px;bottom:0;left:10px;width:fit-content;margin:30px auto;"; break;
    case "bl": case "br": default:
      keyframes.push({ transform: "translateY(100%)", bottom: 0 });
      s = from === "br" ? "right:0;bottom:0;" : "left:0;bottom:0;"; break;
  }
  s = s +"background:" + types[type || "info"] + ";box-shadow: 0 0 10px 2px " + types[type || "info"] + ";";
  keyframes.push({ transform: "translateY(0px)" });
  m.style = s;
  m.textContent = message || o;
  document.body.appendChild(m);
  m.animate(keyframes, { duration: 300 })
  .onfinish = () => {
    m.animate(keyframes, {delay: time || 1000,duration: 300,direction: "reverse"})
    .onfinish = () => {
      m.remove();
    };
  };
}

And use it, In any where in your web app using following code:

// import showToast function by replacing ... with relative path
import {showToast} from '...';
// To show an info message just pass message to showToast function
showToast("This is an info message");

The showToast function accepts either a String or an Object as arguments. To display a simple informational message, pass a String as the message. For more customization, pass an Object with the following properties:

  • message: A string to be displayed as a message or notification.
  • time: The duration, in milliseconds, for which the message is displayed before automatic dismissed. The default duration is 1000 milliseconds (1 second).
  • from: The position of the Toast on the screen. Use bl for bottom-left corner, br for bottom-right corner, tl for top-left corner, tr for top-right corner, and bc for bottom-center. The default position is bottom-left.
  • type: The type of message. Use info for informational, warn for warming, error for error and success for successful messages. The default is informational message. The colors used for message types as follows: { info: "dodgerblue", warn: "darkorange", error: "red", success: "forestgreen" } , you can customize it in first line of JavaScript code.

In this component, I have used slide animations for its dynamic presentation. However, feel free to customize the animation further by modifying the CSS and JavaScript code according to your preferences and requirements.

Alright, I've covered the fundamental aspects, I believe I've addressed the common and necessary points. I hope you'll find this blog post enjoyable and informative, and that it provides you with valuable insights into creating dynamic and customizable Toasts or Snackbars. Happy reading!

Published on Nov 10, 2023
Comments (undefined)

Read More

How to Convert Milliseconds Time into Formatted String (HH:MM:SS) in Java

Hello Developers! in this blog post, we will learn how to convert milliseconds time into formatted String in Java. For example 6548000 milliseconds into 1:49:08, so we can show it as duration to user.

Nov 12, 2023

How to Change Brightness of Only One Activity in Android Using Java

Hello Developers! In this blog post, we will learn how to change the brightness of only one activity, not for the overall application or the entire phone brightness. For example, if the user drags on the screen, changes the progress of the seek bar, or clicks on buttons, then the brightness of the activity should change. This is a feature commonly seen in Video-Player Apps.

Nov 13, 2023

How to Control Volume using Android SeekBar in Java

Hello Developers! In this blog post, we will learn how to change volume using SeekBar in Android using Java. Basically we increase or decrease system volume of phone when progress of SeekBar chnages and show a TextView for volume level.

Nov 15, 2023

How to Remove All Child Elements at Once in JavaScript

Hello, developers! In this blog post, we will learn how to remove all child elements at once from an HTML element using JavaScript. Removing all children at once is a little problematic task on the web because the web does not have any method like removeAll() that removes all children.

Nov 17, 2023

How to Listen to URL Changes in Next.js for a Route or Overall App

Hello Developers, In this blog post, we will see how to listen to URL changes at the route level or application level in a Next.js app. We will create a listener to listen for URL changes in both App Router and Pages Router.

Nov 23, 2023

How to Get Absolute Paths of Internal and External Storages in Android Development

To get paths, we use the ContextCompat.getExternalFilesDirs method. This method returns paths to the files directory (application-specific) on all available external storage devices. The returned paths are not exactly what we want, but we can modify them to suit our needs.

Nov 24, 2023