### Initialize Sonner.js with Custom Options
Source: https://github.com/ofps/sonner-js/blob/main/example/index.html
Initializes the sonner-js library with custom configurations such as disabling the close button, using plain colors, and setting the toast position to bottom-center. This setup ensures toasts appear consistently according to the specified preferences.
```javascript
document.addEventListener("DOMContentLoaded", function () {
Sonner.init({
closeButton: false,
richColors: false,
position: "bottom-center",
});
});
```
--------------------------------
### Display an Info Toast with Sonner.js
Source: https://github.com/ofps/sonner-js/blob/main/example/index.html
Presents an informational toast notification via Sonner.js. This is used to convey general information or updates to the user. The function accepts a message string and depends on Sonner.js being initialized.
```javascript
Sonner.info("Processing your request...");
```
--------------------------------
### Display a Warning Toast with Sonner.js
Source: https://github.com/ofps/sonner-js/blob/main/example/index.html
Renders a warning toast notification using the Sonner.js library. This is employed to alert users about potential issues or non-critical problems. The function takes a message string and requires prior initialization of Sonner.js.
```javascript
Sonner.warning("Please review the details.");
```
--------------------------------
### Display an Error Toast with Sonner.js
Source: https://github.com/ofps/sonner-js/blob/main/example/index.html
Displays an error toast notification using Sonner.js. This is useful for alerting users when an operation has failed. The function expects a message string as an argument and assumes Sonner.js has been initialized.
```javascript
Sonner.error("An error occurred.");
```
--------------------------------
### Display a Success Toast with Sonner.js
Source: https://github.com/ofps/sonner-js/blob/main/example/index.html
Shows a success toast notification using the Sonner.js library. This function is typically called after a successful operation, providing visual feedback to the user. It relies on the Sonner library being initialized beforehand.
```javascript
Sonner.success("Operation successful!");
```
--------------------------------
### Complete Web Application Integration with sonner-js
Source: https://context7.com/ofps/sonner-js/llms.txt
This HTML file demonstrates a full integration of sonner-js within a web application. It includes initializing the library with custom options, displaying various types of toast notifications triggered by button clicks, and handling a form submission with validation and simulated asynchronous feedback. It requires including the sonner-js CSS and JavaScript files.
```html
sonner-js Complete Example
Toast Notification Demo
Form Example
```
--------------------------------
### Initialize Toaster with Options (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code demonstrates how to initialize the sonner-js toaster with custom options. The `init` method accepts an options object to control features like the close button, rich colors, and toast position.
```javascript
Sonner.init({
closeButton: true,
richColors: true,
position: "top-right"
});
```
--------------------------------
### Display a Basic Toast (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code shows how to display a simple toast message using the `Sonner.show` method. This is the most basic way to trigger a toast notification.
```javascript
Sonner.show("My first toast");
```
--------------------------------
### Show Custom Toast with Options (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code demonstrates how to display a custom toast using the `show` method with additional options. It allows specifying the toast type and a description.
```javascript
Sonner.show("Task Completed", {
type: "success",
description: "Your task has been successfully processed."
});
```
--------------------------------
### Sonner API - Initialization
Source: https://github.com/ofps/sonner-js/blob/main/README.md
Initializes the toasters in the DOM with customizable options.
```APIDOC
## init(options)
### Description
Initializes the toasters in the DOM.
### Method
`init`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (Object) - Required - Configuration options for the toaster.
- **closeButton** (boolean) - Optional - Controls the visibility of the close button on the toasts. Defaults to `true`.
- **richColors** (boolean) - Optional - Controls the use of rich colors for the toasts. Defaults to `false`.
- **position** (string) - Optional - Controls the position of the toasts. Possible values are `top-left`, `top-center`, `top-right`, `bottom-left`, `bottom-center`, and `bottom-right`. Defaults to `bottom-right`.
### Request Example
```json
{
"options": {
"closeButton": true,
"richColors": true,
"position": "top-center"
}
}
```
### Response
#### Success Response (200)
No explicit response body is defined for initialization, but the toaster UI will be rendered.
#### Response Example
None
```
--------------------------------
### Initialize Toast System (JavaScript)
Source: https://context7.com/ofps/sonner-js/llms.txt
Initializes the sonner-js toast notification system. It accepts an optional configuration object to customize behavior like the presence of a close button, rich color styling, and the toast's display position. Default settings are applied if no configuration is provided.
```javascript
Sonner.init();
Sonner.init({
closeButton: true,
richColors: true,
position: "bottom-right"
});
Sonner.init({
position: "top-center",
closeButton: false,
richColors: false
});
```
--------------------------------
### Show Warning Toast Notification with Sonner.js
Source: https://context7.com/ofps/sonner-js/llms.txt
Demonstrates various ways to display warning toast notifications using the Sonner.js library. This includes simple messages, warnings before destructive actions, low resource alerts, and notifications for unsaved changes. No specific dependencies are required beyond the Sonner.js library itself.
```javascript
// Simple warning message
Sonner.warning("Your session will expire soon");
// Warning before destructive action
function deleteAccount() {
Sonner.warning("This action cannot be undone");
// Show confirmation dialog
if (confirm("Are you sure you want to delete your account?")) {
// Proceed with deletion
performAccountDeletion();
}
}
// Warning for low resources
function checkDiskSpace(availableSpace) {
if (availableSpace < 100) {
Sonner.warning("Low disk space available");
}
}
// Warning for unsaved changes
window.addEventListener("beforeunload", function(e) {
if (hasUnsavedChanges()) {
Sonner.warning("You have unsaved changes");
e.preventDefault();
e.returnValue = "";
}
});
```
--------------------------------
### Sonner API - Generic Show Toast
Source: https://github.com/ofps/sonner-js/blob/main/README.md
Displays a generic toast with customizable options including type and description.
```APIDOC
## show(msg, options)
### Description
Shows a new toast with a specific message, description, and type.
### Method
`show`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **msg** (string) - Required - The message to display in the toast.
- **options** (Object) - Optional - Additional configuration for the toast.
- **type** (string) - Optional - The type of the toast (e.g., 'success', 'error', 'info', 'warning'). Defaults to 'default'.
- **description** (string) - Optional - The description to display below the main message in the toast.
### Request Example
```javascript
Sonner.show('User logged in', {
type: 'success',
description: 'Welcome back!'
});
```
### Response
#### Success Response (200)
No explicit response body is defined. A custom toast will be displayed.
#### Response Example
None
```
--------------------------------
### Show Info Toast (JavaScript)
Source: https://context7.com/ofps/sonner-js/llms.txt
Displays an informational toast notification using the `info()` method to convey helpful details or tips to the user. This can be used for announcements, guidance, or periodic reminders, and can be triggered on various events like page load or at set intervals.
```javascript
Sonner.info("New features are now available");
function showTutorialTip() {
Sonner.info("Tip: Use Alt+T to expand all notifications");
}
window.addEventListener("DOMContentLoaded", function() {
const isFirstVisit = !localStorage.getItem("visited");
if (isFirstVisit) {
Sonner.info("Welcome to our application!");
localStorage.setItem("visited", "true");
}
});
setInterval(() => {
Sonner.info("Remember to save your work regularly");
}, 300000);
```
--------------------------------
### Show Info Toast (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code displays an informational toast message. The `info` method is suitable for general notifications or tips.
```javascript
Sonner.info("Here is some important information.");
```
--------------------------------
### Sonner API - Toast Notifications
Source: https://github.com/ofps/sonner-js/blob/main/README.md
Methods for displaying different types of toast notifications.
```APIDOC
## success(msg)
### Description
Shows a new success toast with a specific message.
### Method
`success`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **msg** (string) - Required - The message to display in the toast.
### Request Example
```javascript
Sonner.success('Operation completed successfully!');
```
### Response
#### Success Response (200)
No explicit response body is defined. A success toast will be displayed.
#### Response Example
None
```
```APIDOC
## error(msg)
### Description
Shows a new error toast with a specific message.
### Method
`error`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **msg** (string) - Required - The message to display in the toast.
### Request Example
```javascript
Sonner.error('An error occurred during the operation.');
```
### Response
#### Success Response (200)
No explicit response body is defined. An error toast will be displayed.
#### Response Example
None
```
```APIDOC
## info(msg)
### Description
Shows a new info toast with a specific message.
### Method
`info`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **msg** (string) - Required - The message to display in the toast.
### Request Example
```javascript
Sonner.info('This is an informational message.');
```
### Response
#### Success Response (200)
No explicit response body is defined. An info toast will be displayed.
#### Response Example
None
```
```APIDOC
## warning(msg)
### Description
Shows a new warning toast with a specific message.
### Method
`warning`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **msg** (string) - Required - The message to display in the toast.
### Request Example
```javascript
Sonner.warning('Please be cautious with this action.');
```
### Response
#### Success Response (200)
No explicit response body is defined. A warning toast will be displayed.
#### Response Example
None
```
--------------------------------
### Include sonner-js Library (HTML)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This snippet demonstrates how to include the sonner-js library and its CSS file in an HTML project. Ensure the paths to 'sonner.js' and 'sonner.css' are correct for your project structure.
```html
```
--------------------------------
### Show Success Toast (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code displays a success toast message. The `success` method is a shorthand for showing a predefined success-type toast.
```javascript
Sonner.success("Operation completed successfully!");
```
--------------------------------
### Display a Toast via Button Click (HTML)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This HTML snippet shows how to trigger a toast message when a button is clicked. It uses an inline `onclick` event handler to call the `Sonner.show` method with a specific message.
```html
```
--------------------------------
### Show Warning Toast (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code displays a warning toast message. The `warning` method is used to alert the user about potential issues or actions that require attention.
```javascript
Sonner.warning("Please be cautious.");
```
--------------------------------
### Show Error Toast (JavaScript)
Source: https://context7.com/ofps/sonner-js/llms.txt
Displays an error toast notification using the `error()` method to alert users about failures or problems. This is commonly used in API error handling or form validation to provide immediate feedback on issues encountered during operation.
```javascript
Sonner.error("Failed to load data");
fetch("/api/users")
.then(response => {
if (!response.ok) {
throw new Error("Failed to fetch users");
}
return response.json();
})
.catch(error => {
Sonner.error("Unable to load users. Please try again.");
});
function validateForm(formData) {
if (!formData.email) {
Sonner.error("Email address is required");
return false;
}
if (!formData.password || formData.password.length < 8) {
Sonner.error("Password must be at least 8 characters");
return false;
}
return true;
}
```
--------------------------------
### Sonner API - Remove Toast
Source: https://github.com/ofps/sonner-js/blob/main/README.md
Removes a toast from the DOM after a specified delay.
```APIDOC
## remove(id)
### Description
Removes an element with a specific id from the DOM after a delay.
### Method
`remove`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **id** (string) - Required - The data-id attribute of the element to remove.
### Request Example
```javascript
// Assuming a toast has the data-id="toast-123"
Sonner.remove('toast-123');
```
### Response
#### Success Response (200)
No explicit response body is defined. The specified toast will be removed.
#### Response Example
None
```
--------------------------------
### Remove Toast Notification Manually with Sonner.js
Source: https://context7.com/ofps/sonner-js/llms.txt
Explains how to manually remove a specific toast notification from the Sonner.js interface before it auto-dismisses. This involves capturing the toast's ID when it's displayed and then using the `Sonner.remove(id)` function. It also shows how to remove toasts based on user actions.
```javascript
// Show a toast and store its ID for later removal
const toastList = document.getElementById("sonner-toaster-list");
const originalShow = Sonner.show;
// Custom wrapper to capture toast ID
function showRemovableToast(message, options) {
originalShow.call(Sonner, message, options);
// The newest toast is always the first child
const newestToast = toastList.children[0];
return newestToast.getAttribute("data-id");
}
// Usage: Show and remove on demand
const toastId = showRemovableToast("Processing your request...");
// Remove after custom logic completes
setTimeout(() => {
Sonner.remove(toastId);
Sonner.success("Processing complete");
}, 2000);
// Remove toast on user action
const cancelButton = document.getElementById("cancelButton");
cancelButton.addEventListener("click", function() {
const activeToast = document.querySelector('[data-id]');
if (activeToast) {
const id = activeToast.getAttribute("data-id");
Sonner.remove(id);
}
});
```
--------------------------------
### Remove Toast by ID (JavaScript)
Source: https://github.com/ofps/sonner-js/blob/main/README.md
This JavaScript code shows how to remove a specific toast from the DOM using its unique ID. The `remove` method takes the `data-id` attribute of the toast element as an argument.
```javascript
Sonner.remove("toast-id-123");
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.