Implementing a Toast Notification Service
Show how to build a toast notification service as a standalone component to display alerts or information to the user.
// ToastService.js - Toast Notification Service
class ToastService {
constructor() {
this.toasts = [];
}
// Generate toast DOM element
_createToastElement(message, type) {
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerText = message;
return toast;
}
// Show toast message
showToast(message, type = 'info', duration = 3000) {
const toast = this._createToastElement(message, type);
document.body.appendChild(toast);
setTimeout(() => {
document.body.removeChild(toast);
}, duration);
}
}
ToastService class with a method to show toasts. It creates a toast element and removes it from the DOM after a certain duration.
// usage.js - Utilizing the Toast Notification Service
const toastService = new ToastService();
toastService.showToast('Information message', 'info', 5000);
toastService.showToast('Success message', 'success');
toastService.showToast('Error message', 'error', 2000);
Example usage of the ToastService to display different types of toast notifications with various durations.
// styles.css - Basic styles for toast notifications
.toast {
position: fixed;
bottom: 20px;
left: 20px;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: white;
z-index: 1000;
}
.toast.info { color: blue; }
.toast.success { color: green; }
.toast.error { color: red; }
CSS styles for basic toast notifications appearance.