Alertify JS - Documentation

What is AlertifyJS?

AlertifyJS is a JavaScript library designed to provide a simple yet elegant way to display notifications, alerts, and dialog boxes in web applications. It offers a clean, customizable interface that integrates seamlessly with various JavaScript frameworks and projects. Unlike browser’s default alert boxes, AlertifyJS provides more visually appealing and user-friendly alternatives, improving the overall user experience. It allows developers to easily create different types of alerts (success, error, warning, message) with various options for customization.

Key Features and Benefits

Setting up AlertifyJS: Installation and Setup

AlertifyJS can be included in your project using various methods:

1. Using a CDN: The simplest method is to include AlertifyJS via a CDN link in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/alertifyjs/1.13.1/alertify.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/alertifyjs/1.13.1/css/alertify.min.css"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/alertifyjs/1.13.1/css/themes/default.min.css"/>

Remember to replace 1.13.1 with the latest version number if needed. You can also choose different themes.

2. Using npm (for Node.js projects):

If you’re using npm, you can install AlertifyJS using the following command:

npm install alertifyjs

Then, import it into your JavaScript file:

import alertify from 'alertifyjs';

3. Downloading and including locally: Download the AlertifyJS files from the official website and include them in your project’s directory. Then, reference the CSS and JS files in your HTML as shown in the CDN example.

After including AlertifyJS, you’re ready to start using its features.

Basic Usage Examples

Here are some basic examples demonstrating how to use AlertifyJS to display different types of alerts:

1. Simple Alert:

alertify.alert('This is a simple alert message.');

2. Success Alert:

alertify.success('Operation completed successfully!');

3. Error Alert:

alertify.error('An error has occurred.');

4. Warning Alert:

alertify.warning('Please be careful!');

5. Confirm Dialog:

alertify.confirm('Are you sure?', function(e) {
  if (e) {
    alertify.success('Confirmed!');
  } else {
    alertify.error('Cancelled!');
  }
});

These examples showcase the basic functionality of AlertifyJS. Refer to the complete documentation for advanced usage and customization options. Remember to consult the official documentation for the latest version and more detailed information on available options and methods.

Core Notification Methods

Displaying Messages: success, error, warning, log

AlertifyJS provides four core methods for displaying notifications, each conveying a different level of urgency or information:

All methods accept a message string as the first argument. The optional title argument allows adding a title to the notification. The optional callback function is executed after the notification is closed (or dismissed by the user).

Example:

alertify.success('File uploaded successfully!');
alertify.error('Failed to connect to the server.');
alertify.warning('Your session is about to expire.');
alertify.log('User logged in.');

Customizing Notifications: title, message, delay, position

Beyond the basic message display, AlertifyJS offers several options to customize notifications:

Example:

alertify.set('delay', 5000); // Set delay to 5 seconds
alertify.set('position', 'top-right'); // Set position to top-right

alertify.success('Data saved!', 'Success!');

alertify.error('Error: ' + error_message, 'Error', function(){
    //code executed after closing the alert
});

Notification Themes and Styling

AlertifyJS provides several built-in themes, and you can customize the styling further. The default theme is usually sufficient, but you can easily switch to another by including a different theme CSS file (see installation section). For deeper customization, you’ll likely need to modify the provided CSS file directly, or create your own custom CSS to override default styles.

To include a theme, simply link the corresponding CSS file in your HTML. For instance, for the “default” theme (which is usually included by default) you might have something like: <link rel="stylesheet" href="alertify.min.css"> and <link rel="stylesheet" href="themes/default.min.css">. Consult the AlertifyJS documentation for available theme files.

Using Icons in Notifications

AlertifyJS doesn’t inherently include icons in its core notification methods. To add icons, you’ll need to include an icon library (like Font Awesome) and then incorporate the icon classes into the notification’s message string using HTML.

Example (using Font Awesome):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />

<script>
alertify.success('<i class="fas fa-check-circle"></i> File uploaded successfully!');
alertify.error('<i class="fas fa-exclamation-triangle"></i> An error occurred!');
</script>

Remember to replace "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" with the correct path to your icon library’s CSS file. Ensure the icon class names are accurate for the library you use.

Dialog Boxes and Prompts

Creating Confirmation Dialogs

AlertifyJS provides a simple way to create confirmation dialogs using the alertify.confirm() method. This method displays a dialog box with a message and two buttons: “OK” and “Cancel”. The callback function receives a boolean value indicating whether the user clicked “OK” (true) or “Cancel” (false).

alertify.confirm('Are you sure you want to delete this item?', function (e) {
  if (e) {
    // User clicked 'OK'
    alertify.success('Item deleted successfully!');
    // Perform delete operation here
  } else {
    // User clicked 'Cancel'
    alertify.log('Deletion cancelled.');
  }
});

You can customize the text of the buttons using the labels option (see Customizing Dialog Appearance and Behavior).

Creating Prompt Dialogs: Input Fields and Validation

AlertifyJS also allows creating prompt dialogs that include an input field for user input. This is achieved using the alertify.prompt() method. The first argument is the prompt message, the second is a callback function that receives the user’s input (or null if canceled).

alertify.prompt('Please enter your username:', function (e, str) {
  if (e) {
    // User clicked 'OK'
    if (str.length > 0) {
        alertify.success('Username: ' + str);
        // Process username
    } else {
        alertify.error('Username cannot be empty.');
    }
  } else {
    // User clicked 'Cancel'
    alertify.log('Prompt cancelled.');
  }
});

You can perform client-side validation on the input within the callback function before processing it. For more robust validation, server-side validation is recommended.

Customizing Dialog Appearance and Behavior

You can customize the appearance and behavior of dialog boxes using various options:

Example:

alertify.confirm('Overwrite file?', {
  title: 'Confirmation',
  labels: { ok: 'Yes', cancel: 'No' },
  onok: function(){
    //Action on ok
  },
  oncancel: function(){
    //Action on cancel
  }
}, function (e) {
  // Callback for both ok and cancel
});

alertify.prompt('Enter your name', 'Default Name', function (e, str) {
    //Callback
});

Handling Dialog Results and Events

The callback function provided to alertify.confirm() and alertify.prompt() receives the result of the user’s interaction. For alertify.confirm(), it’s a boolean (true for “OK”, false for “Cancel”). For alertify.prompt(), it’s the user’s input string (or null if canceled). You can use this information to perform actions based on the user’s choice. The onok and oncancel options provide alternative ways to handle button clicks without relying solely on the main callback.

Additionally, you might want to listen to other AlertifyJS events. Check the AlertifyJS documentation for a comprehensive list of available events and how to use them. These events might allow you to add more sophisticated handling of dialog interactions and notifications. However, using the callback functions within the dialog functions are the most common and simplest approaches.

Advanced Usage and Customization

Creating Custom Notification Types

While AlertifyJS provides built-in notification types (success, error, warning, log), you can extend its functionality to create custom notification types that match your application’s specific needs. This involves creating a new function that leverages AlertifyJS’s internal mechanisms to display a notification with a unique appearance and behavior. This often requires directly manipulating the AlertifyJS DOM elements or using its internal APIs, which can be complex and requires a thorough understanding of the library’s structure. Direct manipulation of internal elements may break with future updates. A safer approach might be to create a wrapper function that calls existing AlertifyJS methods, adding custom styling using CSS.

Example (Illustrative - Requires understanding AlertifyJS internals; use with caution):

alertify.custom = function(message, options) {
  // Create a new notification element with custom styles based on options
  // ... (Complex DOM manipulation using AlertifyJS internals) ...
};

alertify.custom('This is a custom notification!', { type: 'info', icon: 'info-icon' });

Extending AlertifyJS Functionality

You can extend AlertifyJS’s core functionality by adding new methods or modifying existing ones. This typically involves creating your own JavaScript file and adding to the AlertifyJS namespace. This is highly dependent on the specific version of AlertifyJS used. Check the library’s documentation for guidance on its internal API, which may not always be explicitly documented and might change between versions.

Example (Illustrative – check AlertifyJS API for specific method names and structure):

//In your custom JavaScript file:
alertify.myCustomMethod = function(message){
  //Your custom logic here that uses alertify's existing methods
  alertify.log("Custom Method called: " + message);
}

//In your main js file:
alertify.myCustomMethod("This is a test message");

This approach requires careful consideration to avoid conflicts with existing methods or breaking changes in future AlertifyJS updates.

Integrating with Other JavaScript Frameworks

AlertifyJS is designed to be compatible with various JavaScript frameworks (like React, Angular, Vue.js, etc.). The integration process often involves incorporating AlertifyJS into your framework’s component structure or using its APIs within your framework’s context. For example, in a React application, you might import AlertifyJS and call its methods within component functions. In Angular, you might inject it as a service. The specifics depend on the chosen framework and its integration patterns. Be aware that changes in the AlertifyJS library may affect compatibility, requiring updates to the integration code.

Accessibility Considerations and Best Practices

To ensure your AlertifyJS notifications and dialogs are accessible to users with disabilities, consider the following:

By following these accessibility guidelines, you can create AlertifyJS notifications and dialogs that are usable and inclusive for everyone. Remember to test your implementation thoroughly with different assistive technologies.

API Reference

The following documentation assumes you have included AlertifyJS in your project (refer to the Installation section if needed). Note that argument names in square brackets [] are optional. Specific return values are described where relevant. The behaviour of AlertifyJS might change with new versions; always refer to the official documentation for the latest and most accurate information.

alertify.success(message[, title][, callback])

Displays a success notification.

Returns: undefined

alertify.error(message[, title][, callback])

Displays an error notification.

Returns: undefined

alertify.warning(message[, title][, callback])

Displays a warning notification.

Returns: undefined

alertify.log(message[, title][, callback])

Displays a log message notification.

Returns: undefined

alertify.confirm(message[, options][, callback])

Displays a confirmation dialog.

Returns: undefined

alertify.prompt(message[, defaultValue][, callback])

Displays a prompt dialog with an input field.

Returns: undefined

alertify.set(key, value)

Sets a global setting for AlertifyJS. This affects all subsequent notifications and dialogs. Check the documentation for a list of available settings (e.g., delay, position, buttonReverse).

Returns: undefined

alertify.reset()

Resets all AlertifyJS settings to their default values.

Returns: undefined

alertify.close([instance])

Closes a specific AlertifyJS notification or dialog. If no instance is provided, it attempts to close the most recently opened one. The instance usually comes from the return value of other AlertifyJS methods, although this is not consistent across versions. Consult the AlertifyJS documentation for more information on the return values of the methods.

Returns: undefined

alertify.removeAll()

Closes all currently open AlertifyJS notifications and dialogs.

Returns: undefined

Troubleshooting and Common Issues

Debugging Tips

When encountering issues with AlertifyJS, these debugging techniques can be helpful:

Common Errors and Solutions

Browser Compatibility

AlertifyJS generally supports modern browsers. However, very old or outdated browsers might have compatibility issues. For best results, target browsers that have good JavaScript support and a relatively recent rendering engine. Thoroughly testing your application across different browsers is always recommended.

Known Limitations

Remember to always consult the official AlertifyJS documentation for the most up-to-date information on troubleshooting, compatibility, and known limitations.