Jolty home Jolty Documentation

Toast

Push notifications, alert messages, create your own template and animation with a Toast component.
<button id="show-message" class="btn btn--md btn--primary">Show toast</button>

Getting started

Toast comes without built-in HTML or CSS, so before using it, you need to create a layout for the container using the static Toast.container() method, which will contain our toasts.

js
Toast.container(({ position, name }) => {
  const nameClass = name ? `toasts--${name}` : "";
  const positionClass = position ? `toasts--${position}` : "";
  return `<div class="toasts ${nameClass} ${positionClass}"></div>`;
});

If you want to set different layouts for the container, you can pass the name for it as the first argument and then use the container option when creating a toast.

Next, we need to set a template for the toast using the static Toast.template() method.

js
Toast.template(({ content, type, autohide }) => {
  const className = `toast ${type ? "toast--" + type : ""}`;
  const dismiss = `
      <button class="btn btn--close" data-ui-dismiss aria-label="Close">✕</button>`;
  const progress = autohide ? '<div class="ui-toast-progress" data-ui-progress></div>' : "";
  return `<div class="${className}">${content}${dismiss}${progress}</div>`;
});

Next, depending on the event, we create our toast, which will automatically appear in the default container and with the default template, unless we have specified different names.

js
import { Toast } from "jolty";
 
new Toast({
  autohide: 3000,
  content: `Hello, World!`,
  type: "info",
  transition: "slide-right",
  position: "top-end",
  limit: 4,
});

Options

NameTypeDefaultDescription
initBooleantrueShould the instance be automatically initialized when an instance is created? If false, you’ll need to manually initiate it by calling toast.init().
destroyBooleanfalseAllows you to destroy an instance at a specific breakpoint.
dataString''Allows you to use the default options that have been added through the Toast.data() static method.
onObjectnullUsed to register event handlers.
appearBooleantrueIf you want to apply a transition upon initialization as well, you can set this option to true. Attribute: data-ui-appear
eventPrefixString'ui-toast:'Prefix for events dispatched on the toast element.
eventDispatchBoolean, EventNametrueDefines if events are dispatched or used only within options.
eventBubbleBoolean, EventNametrueDefines if events should bubble up the DOM.
breakpointsObjectnullDefines custom options for specific breakpoints.
shownBooleannullDefines if the toast is open after initialization. By default, it’s null, which means it checks the hidden attribute or another attribute, depending on hideMode.
rootCSSSelector, ElementnullBy default, this is null. If the toast is in the DOM, it will stay in its place. If it is programmatically generated, it will be placed in the body.
containerString''Specifies the container template created with the static method Toast.container().
templateString''Specifies the toast template created with the static method Toast.template().
limitNumbernullDetermines the maximum number of toasts that can be displayed at the same time.
limitAnimateEnterBooleantrueDetermines whether new toasts should be animated if the limit is exceeded.
limitAnimateLeaveBooleantrueDetermines whether old toasts should be animated if the limit is exceeded.
toastClassActiveString'ui-active'CSS class for toast element when it’s shown.
dismissBoolean, CSSSelectortrueAllows the toast to be hide when clicked on the button. By default, it’s true, meaning the hide method will be called when '[data-ui-dismiss=""],[data-ui-dismiss="toast"]' is clicked
contentanynullCan contain anything, used only in template
positionString''How to position the container: Use 'top','bottom','left', or 'right'. You can also append '-start' or '-end' to these positions, such as 'top-end'.
topLayerBooleantrueDetermines whether the toast should be displayed in the top layer, Attribute: data-ui-top-layer
keepTopLayerBooleantrueDetermines whether the toast should be forced to the frontmost position in the top layer when other components are opened in front of it

Autohide

NameTypeDefaultDescription
autohideBoolean, Number, AutohideOptionsfalseObject with autohide options or boolean true to enable with default options. If a number is set, it will be passed to the duration option.
durationNumber0Sets the time in ms after which the toast will hide
durationUpdateFunctionnullThe function is called each time the progress changes, passes arguments { elem, time, progress }
pauseOnMouseBooleantrueShould the timer pause when we hover over the toast with the mouse
resetOnMouseBooleantrueShould the timer reset when we hover over the toast with the mouse
pauseOnFocusBooleantrueShould the timer pause when we focus on the toast
resetOnFocusBooleantrueShould the timer reset when we focus on the toast
visibilityControlBooleanfalseShould the timer pause when the tab is not active
cssVariableString'ui-progress'Name for the css variable, which will record the current progress

Transition

AttributeTypeDefaultDescription
transitionString, Boolean, TransitionOptionstrueObject with transition options or string to set the name option for the transition.
nameString'ui'Defines the name of the transition that will be used to apply CSS rules. Attribute: data-ui-transition-name
cssBooleantrueDefines if the transition should be applied using CSS rules.
cssVariablesBooleantrueAdds special CSS variables during the transition to the toast element and removes them after completion.
enterFunctionnullAccepts a function enter(el, done){}. call the done() callback to indicate transition end
enterActiveString, Object''CSS classes or styles applied during the entire entering phase. Attribute: data-ui-enter-active
enterFromString, Object''CSS classes or styles applied at the start of the entering phase. Attribute: data-ui-enter-from
enterToString, Object''CSS classes or styles applied at the end of the entering phase. Attribute: data-ui-enter-to
leaveFunctionnullAccepts a function leave(el, done){}. call the done() callback to indicate transition end
leaveActiveString, Object''CSS classes or styles applied during the entire leaving phase. Attribute: data-ui-leave-active
leaveFromString, Object''CSS classes or styles applied at the start of the leaving phase. Attribute: data-ui-leave-from
leaveToString, Object''CSS classes or styles applied at the end of the leaving phase. Attribute: data-ui-leave-to
durationNumbernullDefines the duration of the transition. Should be used only when the animation occurs on child elements.

If the cssVariables option is enabled, special CSS variables are added during the transition to toast and are removed after its completion.

NameTypeDescription
--ui-transition-widthNumberThe width of the toast element at the start of the transition.
--ui-transition-heightNumberThe height of the toast element at the start of the transition.

Accessibility (a11y)

NameTypeDefaultDescription
a11yBoolean, String, A11yOptions'status'Object with A11yOptions or true to enable with default options. You can also use one of the following values: 'status' or 'alert'.
roleString'status'Adds the role attribute to the toast element.
ariaLiveString'polite'Adds the aria-live attribute to the toast element.
ariaAtomicBooleantrueAdds the aria-atomic attribute to the toast element.

Defaults for the a11y:'status' value:

{
  role: 'status',
  ariaLive: 'polite',
}

Defaults for the a11y:'alert' value:

{
  role: 'alert',
  ariaLive: 'assertive',
}

Methods

methodreturndescription
init()instanceInitializes the component.
destroy(destroyOptions)instance, nullDestroys the component. Accepts an object as options { remove: false, keepInstance: false, keepState: false }
update(options)instanceAccepts options as an argument and updates the component.
toggle(force, toggleOptions)promiseToggles the component’s visibility state between shown and hidden.
show(toggleOptions)promiseShows the component. Accepts the same options as toggle() method
hide(toggleOptions)promiseHides the component. Accepts the same options as toggle() method

Class

methodreturndescription
data(name?, callback)ClassAllows you to set default options for components that have the property data:'name'
updateDefault(options)defaultUpdates default options
initAll(root)instance[]Searches for elements in root, which defaults to document with the attribute data-ui-toast
get(id or elem)instanceSearches for an instance by id or base element
getOrCreate(id or elem, options)instanceSearches for an instance by id or base element, if not found - creates a new instance with specified options
container(name?, callback)ClassCreates a layout for the container
template(name?, callback)ClassCreates a layout for the toast
toggle(id, force, toggleOptions)promiseSearches for an instance by id and calls its toggle() method with the specified options
show(id, toggleOptions)promiseSearches for an instance by id and calls its show() method with the specified options
hide(id, toggleOptions)promiseSearches for an instance by id and calls its hide() method with the specified options

Properties

NameTypeDescription
idStringThe id of the base / toast element.
isInitBooleanIndicates whether the instance is already initialized.
optsObjectContains the currently applied options for the current breakpoint.
baseOptsObjectContains all options, including the breakpoints option.
base, toastElementAll components have a base property, which refers to the element through which the component is initialized and where events are fired. toast is a synonym for base.

Class

NameTypeDescription
DefaultObjectDefault options
instancesMapA Map that contains all instances of the component

Events

By default, events that are listened to directly through an element have the prefix 'ui-toast:'. This can be changed through the eventPrefix property. Additionally, you can disable the bubbling of these events using eventBubble or turn them off entirely via eventDispatch.

Toast.data("my-toast", {
  on: {
    shown(instance, { trigger, event }) {
      // do something...
    },
    any(eventName, instance, { trigger, event }) {
      if (eventName === "shown") {
        // do something...
      }
    },
  },
});
 
// or directly on the toast element
const toastElem = document.querySelector(".my-toast");
toastElem.addEventListener("ui-toast:show", (e) => {
  const [instance, { trigger, event }] = e.detail;
  // do something...
});
 
// or on the document
document.addEventListener("ui-toast:show", (e) => {
  const [instance, { trigger, event }] = e.detail;
  // do something...
});
NameArgumentsDescription
beforeInitinstanceEvent will fired right before initialization.
initinstanceFires when initialization has been completed.
beforeShowinstance, {trigger, event}Fires immediately when the show() method is called.
showinstance, {trigger, event}Fires when the element becomes visible, but the CSS transition hasn’t started yet.
showninstance, {trigger, event}Fires when the CSS transition hasn’t been completed.
beforeHideinstance, {trigger, event}Fires immediately when the hide() method is called.
hideinstance, {trigger, event}Fires just before the CSS transition starts.
hiddeninstance, {trigger, event}Fires when the CSS transition has been completed.
pauseinstanceFires when the autohide timer is paused.
resumeinstanceFires when the autohide timer is resumed.
resetinstanceFires when the autohide timer is reset.
beforeDestroyinstanceFires before the instance is destroyed.
destroyinstanceFires immediately when the destroy() method is called.
breakpointinstance, breakpoint, prevBreakpointFires when the breakpoint has been changed.
anyeventName, instanceFires on any event occurrence. The first argument contains the name of the event.
2023 © A Project by Jolty Labs 🇪🇸 🇺🇦