Here is a JavaScript implementation of the Notification API as per your requirements, along with the necessary CSS for a sleek and modern UI with smooth animations. This code includes the Notification class with static methods and a supporting NotificationItem class for individual notifications.
<!-- Include this HTML structure in your page -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Notification API Example</title>
<style>
/* Notification styles */
.notification-area {
position: fixed;
bottom: 16px;
right: 16px;
display: flex;
flex-direction: column-reverse;
align-items: flex-end;
z-index: 9999;
}
.notification-container {
width: 300px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
opacity: 0;
transform: translateY(20px);
transition: opacity 0.3s ease, transform 0.3s ease;
padding: 16px;
margin-top: 10px;
color: #000;
}
.notification-dark {
background-color: #333;
color: #fff;
}
.notification-light {
background-color: #fff;
color: #000;
}
.notification-container.show {
opacity: 1;
transform: translateY(0);
}
.notification-container.hide {
opacity: 0;
transform: translateY(20px);
}
.notification-icon {
width: 40px;
height: 40px;
margin-bottom: 8px;
}
.notification-title {
margin: 0;
font-size: 18px;
}
.notification-content {
font-size: 14px;
}
.notification-buttons {
display: flex;
justify-content: flex-end;
margin-top: 16px;
}
.notification-button {
background-color: #007bff;
color: #fff;
border: none;
padding: 8px 12px;
margin-left: 8px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.notification-button:hover {
background-color: #0056b3;
}
.notification-input-container {
display: flex;
margin-top: 16px;
}
.notification-input {
flex-grow: 1;
padding: 8px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
}
.notification-submit-button {
background-color: #28a745;
color: #fff;
border: none;
padding: 8px 12px;
margin-left: 8px;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s ease;
}
.notification-submit-button:hover {
background-color: #218838;
}
</style>
</head>
<body>
<!-- The notification area will be dynamically inserted -->
<script>
// JavaScript code for the Notification API
class Notification {
static historyList = [];
static historyOptions = {
allow: false,
saveAs: 'default',
max: 10
};
static notifications = []; // Keep a list of current notifications
static notificationArea = null;
static show(options) {
if (!Notification.notificationArea) {
// Create the notification area
const area = document.createElement('div');
area.classList.add('notification-area');
document.body.appendChild(area);
Notification.notificationArea = area;
}
const notification = new NotificationItem(options);
Notification.notifications.push(notification);
Notification.notificationArea.appendChild(notification.element);
}
static history(options) {
// Merge options into historyOptions
Notification.historyOptions = {
...Notification.historyOptions,
...options
};
if (Notification.historyOptions.allow) {
// Load existing history
const savedHistory = localStorage.getItem(Notification.historyOptions.saveAs);
if (savedHistory) {
Notification.historyList = JSON.parse(savedHistory);
} else {
Notification.historyList = [];
}
} else {
Notification.historyList = [];
}
}
static updateHistory(notificationData) {
if (Notification.historyOptions.allow) {
Notification.historyList.unshift(notificationData); // Add to beginning
if (Notification.historyList.length > Notification.historyOptions.max) {
Notification.historyList.pop(); // Remove oldest
}
localStorage.setItem(Notification.historyOptions.saveAs, JSON.stringify(Notification.historyList));
}
}
static forceRemove() {
Notification.notifications.forEach(notif => {
notif.remove();
});
Notification.notifications = [];
// Clear historyList
Notification.historyList = [];
// Remove from localStorage
if (Notification.historyOptions.allow) {
localStorage.removeItem(Notification.historyOptions.saveAs);
}
}
}
class NotificationItem {
constructor(options) {
this.options = options;
this.createNotification();
}
createNotification() {
const { title, content, optional = {}, theme } = this.options;
const { buttons = [], icon } = optional;
// Determine the actual theme
let actualTheme = theme || 'light';
if (theme === 'user-prefers') {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
actualTheme = 'dark';
} else {
actualTheme = 'light';
}
}
// Create main container
const container = document.createElement('div');
container.classList.add('notification-container', `notification-${actualTheme}`);
// Create icon if provided
if (icon) {
const img = new Image();
img.src = icon;
img.onload = () => {
if (img.naturalWidth !== img.naturalHeight) {
throw new Error('Icon dimensions must be square');
} else {
const iconElement = document.createElement('img');
iconElement.src = icon;
iconElement.classList.add('notification-icon');
container.insertBefore(iconElement, container.firstChild);
}
}
}
// Title
if (title) {
const titleElement = document.createElement('h2');
titleElement.textContent = title;
titleElement.classList.add('notification-title');
container.appendChild(titleElement);
}
// Content
if (content) {
const contentElement = document.createElement('p');
contentElement.textContent = content;
contentElement.classList.add('notification-content');
container.appendChild(contentElement);
}
// Buttons
if (buttons.length > 0) {
const buttonsContainer = document.createElement('div');
buttonsContainer.classList.add('notification-buttons');
buttons.forEach(button => {
const buttonElement = document.createElement('button');
buttonElement.textContent = button.text;
buttonElement.classList.add('notification-button');
buttonElement.addEventListener('click', () => {
button.click(this);
});
buttonsContainer.appendChild(buttonElement);
});
container.appendChild(buttonsContainer);
}
// Reference to the element
this.element = container;
// Add animation for showing
setTimeout(() => {
container.classList.add('show');
}, 10);
// Save to history
Notification.updateHistory({
title: this.options.title,
content: this.options.content,
timestamp: new Date().toISOString(),
});
}
deny() {
// Implement deny action, e.g., remove notification
this.remove();
}
showInput(placeholderText, buttonText, callback) {
// Show an input field within the notification
const inputContainer = document.createElement('div');
inputContainer.classList.add('notification-input-container');
const inputElement = document.createElement('input');
inputElement.classList.add('notification-input');
inputElement.placeholder = placeholderText;
const submitButton = document.createElement('button');
submitButton.classList.add('notification-submit-button');
submitButton.textContent = buttonText;
submitButton.addEventListener('click', () => {
const value = inputElement.value;
callback(value);
this.remove();
});
inputContainer.appendChild(inputElement);
inputContainer.appendChild(submitButton);
this.element.appendChild(inputContainer);
}
remove() {
// Remove the notification with animation
this.element.classList.remove('show');
this.element.classList.add('hide');
setTimeout(() => {
// Remove from DOM
this.element.remove();
// Remove from notifications array
const index = Notification.notifications.indexOf(this);
if (index > -1) {
Notification.notifications.splice(index, 1);
}
}, 300); // Duration should match CSS animation duration
}
}
// Example usage
// Set up notification history options
Notification.history({
allow: true, // Enable history
saveAs: 'Messages', // Storage key
max: 5, // Max history entries
});
// Show a notification
Notification.show({
title: 'Message',
content: 'Hey, wanna go out?',
optional: {
buttons: [
{
text: 'Deny',
click: n => {
n.deny();
}
},
{
text: 'Reply',
click: n => {
n.showInput('Enter a message...', 'Send', (message) => {
// Do sending actions with the message
console.log('Message sent:', message);
}); // First argument is placeholder, second is button text, third is callback
}
}
],
icon: './assets/icon.ico' // Icon must be square (e.g., 256x256)
},
theme: 'dark' // 'dark', 'light', or 'user-prefers'
});
// Access the history list
console.log(Notification.historyList);
// Force remove all notifications
// Notification.forceRemove();
</script>
</body>
</html>
Explanation:
-
Notification Class:
Notification.show(options): Displays a new notification with the provided options.
Notification.history(options): Configures history settings and loads existing history from localStorage if enabled.
Notification.forceRemove(): Removes all active notifications and clears the history.
Notification.historyList: An array containing the history of notifications.
-
NotificationItem Class:
- Handles the creation and behavior of individual notifications.
n.deny(): Removes the notification.
n.showInput(placeholderText, buttonText, callback): Displays an input field within the notification.
-
Styles:
- The CSS styles provide a modern look with smooth transitions for showing and hiding notifications.
- Themes are supported via the
theme option ('dark', 'light', or 'user-prefers').
- Smooth animations are achieved using CSS transitions on the
opacity and transform properties.
-
Icon Handling:
- If an
icon is provided, the code checks that the image dimensions are square and throws an error if not.
-
History Management:
- If history is enabled through
Notification.history(), notifications are saved to localStorage under the specified key.
- The history list is capped at the number specified by
max.
-
Usage Example:
- The script includes an example that demonstrates how to display a notification with custom buttons and actions.
- The
Reply button shows an input field for the user to enter a message.
- The
Deny button simply closes the notification.
Note: Ensure that the path to the icon image ('./assets/icon.ico') is correct relative to your HTML file. Also, include the CSS styles in the <style> tag or an external stylesheet.
To Use the Notification API:
- Include the JavaScript and CSS code in your HTML page.
- Customize the notifications by calling
Notification.show() with your desired options.
- Configure history management by calling
Notification.history().
- Access the history via
Notification.historyList.
Feel free to adjust the styles and functionality to better suit your application's needs.