ToastrJS is a JavaScript library for Gnome / Growl type non-blocking notifications.
npx @tessl/cli install tessl/npm-toastr@2.1.00
# Toastr
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: toastr
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install toastr`
10
- **Dependencies**: jQuery >=1.12.0
11
12
## Core Imports
13
14
ESM (if using a module bundler):
15
```javascript
16
import toastr from "toastr";
17
import "toastr/build/toastr.min.css";
18
```
19
20
CommonJS:
21
```javascript
22
const toastr = require("toastr");
23
```
24
25
Browser (global):
26
```html
27
<link href="toastr.css" rel="stylesheet"/>
28
<script src="jquery.js"></script>
29
<script src="toastr.js"></script>
30
<!-- toastr is now available as window.toastr -->
31
```
32
33
## Basic Usage
34
35
```javascript
36
// Display basic notifications
37
toastr.info('Information message');
38
toastr.success('Success message', 'Well done!');
39
toastr.warning('Warning message', 'Be careful');
40
toastr.error('Error message', 'Something went wrong');
41
42
// Clear all notifications
43
toastr.clear();
44
45
// Remove notifications immediately
46
toastr.remove();
47
```
48
49
## Architecture
50
51
Toastr is built around several key components:
52
53
- **Notification Methods**: Four main methods (`info`, `success`, `warning`, `error`) for different message types
54
- **Container Management**: Automated toast container creation and positioning
55
- **Options System**: Global options object with per-notification overrides
56
- **Event System**: Subscription model for toast lifecycle events
57
- **Animation Engine**: jQuery-based animations with configurable methods and timing
58
- **UMD Module**: Universal module definition supporting AMD, CommonJS, and global usage
59
60
## Capabilities
61
62
### Display Notifications
63
64
Display toast notifications with different severity levels and optional customization.
65
66
```javascript { .api }
67
/**
68
* Display an info notification
69
* @param message - The notification message (optional)
70
* @param title - The notification title (optional)
71
* @param optionsOverride - Options to override defaults (optional)
72
* @returns jQuery element representing the toast
73
*/
74
function info(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;
75
76
/**
77
* Display a success notification
78
* @param message - The notification message (optional)
79
* @param title - The notification title (optional)
80
* @param optionsOverride - Options to override defaults (optional)
81
* @returns jQuery element representing the toast
82
*/
83
function success(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;
84
85
/**
86
* Display a warning notification
87
* @param message - The notification message (optional)
88
* @param title - The notification title (optional)
89
* @param optionsOverride - Options to override defaults (optional)
90
* @returns jQuery element representing the toast
91
*/
92
function warning(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;
93
94
/**
95
* Display an error notification
96
* @param message - The notification message (optional)
97
* @param title - The notification title (optional)
98
* @param optionsOverride - Options to override defaults (optional)
99
* @returns jQuery element representing the toast
100
*/
101
function error(message?: string, title?: string, optionsOverride?: ToastrOptions): JQuery;
102
```
103
104
**Usage Examples:**
105
106
```javascript
107
// Basic notifications
108
toastr.info('Processing your request...');
109
toastr.success('File uploaded successfully!', 'Upload Complete');
110
toastr.warning('Session will expire in 5 minutes', 'Session Warning');
111
toastr.error('Failed to save changes', 'Save Error');
112
113
// With options override
114
toastr.success('Important message', 'Success', {
115
timeOut: 10000,
116
closeButton: true,
117
progressBar: true
118
});
119
120
// Get the toast element for further manipulation
121
const $toast = toastr.info('Loading...', 'Please wait');
122
// Later: $toast.find('.custom-button').click(handleClick);
123
```
124
125
### Container Management
126
127
Manage the toast container that holds all notifications.
128
129
```javascript { .api }
130
/**
131
* Get the toast container element, optionally creating it
132
* @param options - Container options (optional, uses defaults if not provided)
133
* @param create - Whether to create container if it doesn't exist (optional)
134
* @returns jQuery element representing the container
135
*/
136
function getContainer(options?: ToastrOptions, create?: boolean): JQuery;
137
138
/**
139
* Clear toasts with hide animation
140
* @param toastElement - Specific toast to clear, or all if omitted (optional)
141
* @param clearOptions - Clear options (optional)
142
* @returns undefined
143
*/
144
function clear(toastElement?: JQuery, clearOptions?: ClearOptions): void;
145
146
/**
147
* Remove toasts immediately without animation
148
* @param toastElement - Specific toast to remove, or all if omitted (optional)
149
* @returns undefined
150
*/
151
function remove(toastElement?: JQuery): void;
152
```
153
154
**Usage Examples:**
155
156
```javascript
157
// Get container (creates if doesn't exist)
158
const $container = toastr.getContainer();
159
160
// Clear specific toast with animation
161
const $toast = toastr.info('Temporary message');
162
toastr.clear($toast);
163
164
// Clear all toasts
165
toastr.clear();
166
167
// Force clear even focused toasts
168
toastr.clear($toast, { force: true });
169
170
// Remove immediately without animation
171
toastr.remove();
172
```
173
174
### Event System
175
176
Subscribe to toast lifecycle events for custom handling.
177
178
```javascript { .api }
179
/**
180
* Subscribe to toast events (pass null to unsubscribe)
181
* @param callback - Function called with event data, or null to unsubscribe
182
* @returns undefined
183
*/
184
function subscribe(callback: ((response: ToastrResponse) => void) | null): void;
185
```
186
187
**Usage Examples:**
188
189
```javascript
190
// Subscribe to all toast events
191
toastr.subscribe(function(response) {
192
console.log('Toast event:', response.state); // 'visible' or 'hidden'
193
console.log('Toast ID:', response.toastId);
194
console.log('Options used:', response.options);
195
console.log('Start time:', response.startTime);
196
if (response.endTime) {
197
console.log('End time:', response.endTime);
198
}
199
});
200
201
// Unsubscribe
202
toastr.subscribe(null);
203
204
// Track only success notifications
205
toastr.subscribe(function(response) {
206
if (response.options.iconClass === 'toast-success') {
207
analytics.track('success_notification_shown');
208
}
209
});
210
```
211
212
### Configuration
213
214
Global configuration through the options object and per-notification overrides.
215
216
```javascript { .api }
217
/**
218
* Global options object - modify to change default behavior
219
*/
220
const options: ToastrOptions;
221
222
/**
223
* Library version string
224
*/
225
const version: string;
226
```
227
228
**Usage Examples:**
229
230
```javascript
231
// Configure global defaults
232
toastr.options.timeOut = 3000;
233
toastr.options.positionClass = 'toast-bottom-right';
234
toastr.options.closeButton = true;
235
236
// Override for specific notification
237
toastr.success('Saved!', 'Success', {
238
timeOut: 0, // Make it sticky
239
onclick: function() {
240
window.location.href = '/dashboard';
241
}
242
});
243
244
// Get version
245
console.log('Toastr version:', toastr.version); // "2.1.4"
246
```
247
248
## Types
249
250
```javascript { .api }
251
interface ToastrOptions {
252
// Display timing
253
timeOut?: number; // Auto-hide delay in ms (default: 5000)
254
extendedTimeOut?: number; // Extended delay on hover (default: 1000)
255
tapToDismiss?: boolean; // Click to dismiss (default: true)
256
257
// Animation options
258
showMethod?: string; // jQuery show method (default: 'fadeIn')
259
showDuration?: number; // Show animation duration (default: 300)
260
showEasing?: string; // Show animation easing (default: 'swing')
261
hideMethod?: string; // jQuery hide method (default: 'fadeOut')
262
hideDuration?: number; // Hide animation duration (default: 1000)
263
hideEasing?: string; // Hide animation easing (default: 'swing')
264
closeMethod?: string | boolean; // Close button animation method (default: false)
265
closeDuration?: number | boolean; // Close button animation duration (default: false)
266
closeEasing?: string | boolean; // Close button animation easing (default: false)
267
268
// Positioning and layout
269
positionClass?: string; // Container position class (default: 'toast-top-right')
270
containerId?: string; // Container element ID (default: 'toast-container')
271
target?: string; // Container parent selector (default: 'body')
272
newestOnTop?: boolean; // Stack order (default: true)
273
274
// Visual styling
275
toastClass?: string; // Base toast CSS class (default: 'toast')
276
titleClass?: string; // Title element CSS class (default: 'toast-title')
277
messageClass?: string; // Message element CSS class (default: 'toast-message')
278
iconClass?: string; // Default icon CSS class (default: 'toast-info')
279
iconClasses?: IconClasses; // Icon classes for each type
280
281
// Close button
282
closeButton?: boolean; // Enable close button (default: false)
283
closeHtml?: string; // Close button HTML (default: '<button type="button">×</button>')
284
closeClass?: string; // Close button CSS class (default: 'toast-close-button')
285
closeOnHover?: boolean; // Pause on hover (default: true)
286
287
// Progress bar
288
progressBar?: boolean; // Show progress bar (default: false)
289
progressClass?: string; // Progress bar CSS class (default: 'toast-progress')
290
291
// Content options
292
escapeHtml?: boolean; // HTML-escape content (default: false)
293
rtl?: boolean; // Right-to-left support (default: false)
294
preventDuplicates?: boolean; // Prevent identical sequential toasts (default: false)
295
296
// Event callbacks
297
onShown?: () => void; // Called when toast is shown
298
onHidden?: () => void; // Called when toast is hidden
299
onclick?: (event: Event) => void; // Called when toast is clicked
300
onCloseClick?: (event: Event) => void; // Called when close button is clicked
301
302
// Debug
303
debug?: boolean; // Enable console logging (default: false)
304
}
305
306
interface IconClasses {
307
error: string; // Error icon class (default: 'toast-error')
308
info: string; // Info icon class (default: 'toast-info')
309
success: string; // Success icon class (default: 'toast-success')
310
warning: string; // Warning icon class (default: 'toast-warning')
311
}
312
313
interface ClearOptions {
314
force?: boolean; // Force clear even if toast has focus
315
}
316
317
interface ToastrResponse {
318
toastId: number; // Unique toast identifier
319
state: 'visible' | 'hidden'; // Current toast state
320
startTime: Date; // When toast was created
321
endTime?: Date; // When toast was hidden (if applicable)
322
options: ToastrOptions; // Options used for this toast
323
map: object; // Internal toast data
324
}
325
```
326
327
## Position Classes
328
329
Available values for `positionClass` option:
330
331
- `toast-top-right` (default)
332
- `toast-top-left`
333
- `toast-top-center`
334
- `toast-bottom-right`
335
- `toast-bottom-left`
336
- `toast-bottom-center`
337
338
## Advanced Usage Examples
339
340
### Custom Styling and Animations
341
342
```javascript
343
// Custom animation with easing
344
toastr.options.showMethod = 'slideDown';
345
toastr.options.hideMethod = 'slideUp';
346
toastr.options.showEasing = 'easeOutBounce';
347
toastr.options.hideEasing = 'easeInBack';
348
349
// Progress bar with extended timeout
350
toastr.options.progressBar = true;
351
toastr.options.timeOut = 10000;
352
toastr.options.extendedTimeOut = 5000;
353
```
354
355
### Event-Driven Workflows
356
357
```javascript
358
// Auto-redirect on success
359
toastr.success('Login successful!', 'Welcome', {
360
timeOut: 2000,
361
onHidden: function() {
362
window.location.href = '/dashboard';
363
}
364
});
365
366
// Confirmation workflow
367
toastr.info('Click to confirm action', 'Confirmation Required', {
368
timeOut: 0, // Sticky
369
onclick: function() {
370
performAction();
371
toastr.clear();
372
toastr.success('Action completed!');
373
}
374
});
375
```
376
377
### Complex Configuration
378
379
```javascript
380
// Configure for right-to-left languages with custom styling
381
toastr.options = {
382
...toastr.options,
383
rtl: true,
384
positionClass: 'toast-top-left',
385
closeButton: true,
386
progressBar: true,
387
preventDuplicates: true,
388
escapeHtml: true,
389
closeHtml: '<button type="button" class="custom-close">×</button>',
390
onShown: function() {
391
console.log('Toast displayed');
392
},
393
onHidden: function() {
394
console.log('Toast hidden');
395
}
396
};
397
```
398
399
### Error Handling
400
401
```javascript
402
// Network error with retry option
403
function showNetworkError(retryFn) {
404
const $toast = toastr.error(
405
'Connection failed. <button class="retry-btn">Retry</button>',
406
'Network Error',
407
{
408
timeOut: 0, // Sticky
409
closeButton: true,
410
escapeHtml: false // Allow HTML for button
411
}
412
);
413
414
$toast.find('.retry-btn').click(function() {
415
toastr.clear($toast);
416
retryFn();
417
});
418
}
419
420
// Validation errors
421
function showValidationErrors(errors) {
422
errors.forEach(error => {
423
toastr.error(error.message, error.field, {
424
timeOut: 8000
425
});
426
});
427
}
428
```