or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-toastr

ToastrJS is a JavaScript library for Gnome / Growl type non-blocking notifications.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/toastr@2.1.x

To install, run

npx @tessl/cli install tessl/npm-toastr@2.1.0

index.mddocs/

Toastr

Toastr is a JavaScript library for displaying non-blocking toast notifications inspired by Gnome/Growl desktop notifications. It provides a simple API for showing info, success, warning, and error messages with extensive customization options including animations, positioning, timeouts, and styling.

Package Information

  • Package Name: toastr
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install toastr
  • Dependencies: jQuery >=1.12.0

Core Imports

ESM (if using a module bundler):

import toastr from "toastr";
import "toastr/build/toastr.min.css";

CommonJS:

const toastr = require("toastr");

Browser (global):

<link href="toastr.css" rel="stylesheet"/>
<script src="jquery.js"></script>
<script src="toastr.js"></script>
<!-- toastr is now available as window.toastr -->

Basic Usage

// Display basic notifications
toastr.info('Information message');
toastr.success('Success message', 'Well done!');
toastr.warning('Warning message', 'Be careful');
toastr.error('Error message', 'Something went wrong');

// Clear all notifications
toastr.clear();

// Remove notifications immediately
toastr.remove();

Architecture

Toastr is built around several key components:

  • Notification Methods: Four main methods (info, success, warning, error) for different message types
  • Container Management: Automated toast container creation and positioning
  • Options System: Global options object with per-notification overrides
  • Event System: Subscription model for toast lifecycle events
  • Animation Engine: jQuery-based animations with configurable methods and timing
  • UMD Module: Universal module definition supporting AMD, CommonJS, and global usage

Capabilities

Display Notifications

Display toast notifications with different severity levels and optional customization.

/**
 * Display an info notification
 * @param message - The notification message (optional)
 * @param title - The notification title (optional)  
 * @param optionsOverride - Options to override defaults (optional)
 * @returns jQuery element representing the toast
 */
function info(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;

/**
 * Display a success notification
 * @param message - The notification message (optional)
 * @param title - The notification title (optional)
 * @param optionsOverride - Options to override defaults (optional)  
 * @returns jQuery element representing the toast
 */
function success(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;

/**
 * Display a warning notification
 * @param message - The notification message (optional)
 * @param title - The notification title (optional)
 * @param optionsOverride - Options to override defaults (optional)
 * @returns jQuery element representing the toast
 */
function warning(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;

/**
 * Display an error notification  
 * @param message - The notification message (optional)
 * @param title - The notification title (optional)
 * @param optionsOverride - Options to override defaults (optional)
 * @returns jQuery element representing the toast
 */
function error(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;

Usage Examples:

// Basic notifications
toastr.info('Processing your request...');
toastr.success('File uploaded successfully!', 'Upload Complete');
toastr.warning('Session will expire in 5 minutes', 'Session Warning');
toastr.error('Failed to save changes', 'Save Error');

// With options override
toastr.success('Important message', 'Success', {
  timeOut: 10000,
  closeButton: true,
  progressBar: true
});

// Get the toast element for further manipulation
const $toast = toastr.info('Loading...', 'Please wait');
// Later: $toast.find('.custom-button').click(handleClick);

Container Management

Manage the toast container that holds all notifications.

/**
 * Get the toast container element, optionally creating it
 * @param options - Container options (optional, uses defaults if not provided)  
 * @param create - Whether to create container if it doesn't exist (optional)
 * @returns jQuery element representing the container
 */
function getContainer(options?: ToastrOptions, create?: boolean): JQuery;

/**
 * Clear toasts with hide animation
 * @param toastElement - Specific toast to clear, or all if omitted (optional)
 * @param clearOptions - Clear options (optional)  
 * @returns undefined
 */
function clear(toastElement?: JQuery, clearOptions?: ClearOptions): void;

/**
 * Remove toasts immediately without animation
 * @param toastElement - Specific toast to remove, or all if omitted (optional)
 * @returns undefined  
 */
function remove(toastElement?: JQuery): void;

Usage Examples:

// Get container (creates if doesn't exist)
const $container = toastr.getContainer();

// Clear specific toast with animation
const $toast = toastr.info('Temporary message');
toastr.clear($toast);

// Clear all toasts
toastr.clear();

// Force clear even focused toasts
toastr.clear($toast, { force: true });

// Remove immediately without animation
toastr.remove();

Event System

Subscribe to toast lifecycle events for custom handling.

/**
 * Subscribe to toast events (pass null to unsubscribe)
 * @param callback - Function called with event data, or null to unsubscribe
 * @returns undefined
 */  
function subscribe(callback: ((response: ToastrResponse) => void) | null): void;

Usage Examples:

// Subscribe to all toast events
toastr.subscribe(function(response) {
  console.log('Toast event:', response.state); // 'visible' or 'hidden'
  console.log('Toast ID:', response.toastId);
  console.log('Options used:', response.options);
  console.log('Start time:', response.startTime);
  if (response.endTime) {
    console.log('End time:', response.endTime);
  }
});

// Unsubscribe
toastr.subscribe(null);

// Track only success notifications
toastr.subscribe(function(response) {
  if (response.options.iconClass === 'toast-success') {
    analytics.track('success_notification_shown');
  }
});

Configuration

Global configuration through the options object and per-notification overrides.

/**
 * Global options object - modify to change default behavior
 */
const options: ToastrOptions;

/**
 * Library version string
 */  
const version: string;

Usage Examples:

// Configure global defaults
toastr.options.timeOut = 3000;
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.closeButton = true;

// Override for specific notification
toastr.success('Saved!', 'Success', {
  timeOut: 0, // Make it sticky
  onclick: function() {
    window.location.href = '/dashboard';
  }
});

// Get version
console.log('Toastr version:', toastr.version); // "2.1.4"

Types

interface ToastrOptions {
  // Display timing
  timeOut?: number; // Auto-hide delay in ms (default: 5000)
  extendedTimeOut?: number; // Extended delay on hover (default: 1000)
  tapToDismiss?: boolean; // Click to dismiss (default: true)
  
  // Animation options  
  showMethod?: string; // jQuery show method (default: 'fadeIn')
  showDuration?: number; // Show animation duration (default: 300)
  showEasing?: string; // Show animation easing (default: 'swing')
  hideMethod?: string; // jQuery hide method (default: 'fadeOut')
  hideDuration?: number; // Hide animation duration (default: 1000)  
  hideEasing?: string; // Hide animation easing (default: 'swing')
  closeMethod?: string | boolean; // Close button animation method (default: false)
  closeDuration?: number | boolean; // Close button animation duration (default: false)
  closeEasing?: string | boolean; // Close button animation easing (default: false)
  
  // Positioning and layout
  positionClass?: string; // Container position class (default: 'toast-top-right')
  containerId?: string; // Container element ID (default: 'toast-container')  
  target?: string; // Container parent selector (default: 'body')
  newestOnTop?: boolean; // Stack order (default: true)
  
  // Visual styling
  toastClass?: string; // Base toast CSS class (default: 'toast')
  titleClass?: string; // Title element CSS class (default: 'toast-title')
  messageClass?: string; // Message element CSS class (default: 'toast-message')
  iconClass?: string; // Default icon CSS class (default: 'toast-info')
  iconClasses?: IconClasses; // Icon classes for each type
  
  // Close button
  closeButton?: boolean; // Enable close button (default: false)
  closeHtml?: string; // Close button HTML (default: '<button type="button">&times;</button>')
  closeClass?: string; // Close button CSS class (default: 'toast-close-button')
  closeOnHover?: boolean; // Pause on hover (default: true)
  
  // Progress bar
  progressBar?: boolean; // Show progress bar (default: false)
  progressClass?: string; // Progress bar CSS class (default: 'toast-progress')
  
  // Content options
  escapeHtml?: boolean; // HTML-escape content (default: false)
  rtl?: boolean; // Right-to-left support (default: false)
  preventDuplicates?: boolean; // Prevent identical sequential toasts (default: false)
  
  // Event callbacks
  onShown?: () => void; // Called when toast is shown
  onHidden?: () => void; // Called when toast is hidden
  onclick?: (event: Event) => void; // Called when toast is clicked  
  onCloseClick?: (event: Event) => void; // Called when close button is clicked
  
  // Debug
  debug?: boolean; // Enable console logging (default: false)
}

interface IconClasses {
  error: string; // Error icon class (default: 'toast-error')
  info: string; // Info icon class (default: 'toast-info')  
  success: string; // Success icon class (default: 'toast-success')
  warning: string; // Warning icon class (default: 'toast-warning')
}

interface ClearOptions {
  force?: boolean; // Force clear even if toast has focus
}

interface ToastrResponse {
  toastId: number; // Unique toast identifier
  state: 'visible' | 'hidden'; // Current toast state
  startTime: Date; // When toast was created
  endTime?: Date; // When toast was hidden (if applicable)
  options: ToastrOptions; // Options used for this toast
  map: object; // Internal toast data
}

Position Classes

Available values for positionClass option:

  • toast-top-right (default)
  • toast-top-left
  • toast-top-center
  • toast-bottom-right
  • toast-bottom-left
  • toast-bottom-center

Advanced Usage Examples

Custom Styling and Animations

// Custom animation with easing
toastr.options.showMethod = 'slideDown';
toastr.options.hideMethod = 'slideUp';
toastr.options.showEasing = 'easeOutBounce';
toastr.options.hideEasing = 'easeInBack';

// Progress bar with extended timeout
toastr.options.progressBar = true;
toastr.options.timeOut = 10000;
toastr.options.extendedTimeOut = 5000;

Event-Driven Workflows

// Auto-redirect on success
toastr.success('Login successful!', 'Welcome', {
  timeOut: 2000,
  onHidden: function() {
    window.location.href = '/dashboard';
  }
});

// Confirmation workflow
toastr.info('Click to confirm action', 'Confirmation Required', {
  timeOut: 0, // Sticky
  onclick: function() {
    performAction();
    toastr.clear();
    toastr.success('Action completed!');
  }
});

Complex Configuration

// Configure for right-to-left languages with custom styling
toastr.options = {
  ...toastr.options,
  rtl: true,
  positionClass: 'toast-top-left',
  closeButton: true,
  progressBar: true,
  preventDuplicates: true,
  escapeHtml: true,
  closeHtml: '<button type="button" class="custom-close">×</button>',
  onShown: function() {
    console.log('Toast displayed');
  },
  onHidden: function() {
    console.log('Toast hidden');  
  }
};

Error Handling

// Network error with retry option
function showNetworkError(retryFn) {
  const $toast = toastr.error(
    'Connection failed. <button class="retry-btn">Retry</button>',
    'Network Error',
    {
      timeOut: 0, // Sticky
      closeButton: true,
      escapeHtml: false // Allow HTML for button
    }
  );
  
  $toast.find('.retry-btn').click(function() {
    toastr.clear($toast);
    retryFn();
  });
}

// Validation errors
function showValidationErrors(errors) {
  errors.forEach(error => {
    toastr.error(error.message, error.field, {
      timeOut: 8000
    });
  });
}