Tooltipster

repository·master·Indexed 25 days ago

https://github.com/calebjacob/tooltipster

A flexible and extensible jQuery plugin for creating modern tooltips. Version 4.2.8 supports major browsers (including IE6+) and requires jQuery 1.10+. It features a comprehensive set of configuration options, instance and core methods, and a plugin system for extending functionality at both the core and instance levels.

Tokens
4K
Snippets
6
Records
15
Agent score
33%

What's inside tooltipster

  1. Overview of Tooltipster

    master

    Tooltipster is a flexible and extensible jQuery plugin used to create modern tooltips. It is compatible with major browsers including Mozilla Firefox, Google Chrome, and IE6+.

    Requirements:

    • jQuery 1.10+ (or lower, depending on specific compatibility needs).

    Size:

    • Default CSS and JS files are approximately 10Kb gzipped.
  2. Implement a Tooltipster plugin

    master

    To create a Tooltipster plugin, use the $.tooltipster._plugin() method. A plugin can provide functionality at the core level (accessible via $.tooltipster.methodName) or the instance level (accessible via instance.methodName).

    Plugin Structure

    • Core level: Use the core object to define methods that act on all tooltips. Use __init to receive the core reference.
    • Instance level: Use the instance object to define methods for specific tooltips. Use __init to receive the instance reference and __destroy to clean up listeners.
    • Options: Use __defaults within the instance object to define default configuration values.

    Best Practices

    • UMD Compliance: Wrap your plugin in a UMD (Universal Module Definition) pattern to support AMD, CommonJS, and global script loading.
    • Chaining: Public methods should return the object they are attached to (either the core or the instance) to allow method chaining.
    • Namespacing: Namespace your event listeners (e.g., pluginName-randomID) and unbind them in the __destroy method to prevent conflicts.
    • File Naming: If your plugin is named myNamespace.myPlugin, name the file tooltipster-myPlugin.js.
    (function(root, factory) {
        if (typeof define === 'function' && define.amd) {
            define(['tooltipster'], function($) {
                return (factory($));
            });
        }
        else if (typeof exports === 'object') {
            module.exports = factory(require('tooltipster'));
        }
        else {
            factory(jQuery);
        }
    }(this, function($) {
    
        var pluginName = 'NAMESPACE.PLUGINNAME';
        
        $.tooltipster._plugin({
            name: pluginName,
            core: {
                __init: function(core) {
                    this.__core = core;
                },
                MYCOREPUBLICMETHOD: function() {
                    return this.__core;
                }
            },
            instance: {
                __defaults: function() {
                    return {
                         /* YOUR DEFAULT OPTIONS HERE */
                    };
                },
                __init: function(instance) {
                    var self = this;
                    self.__instance = instance;
                    self.__namespace = pluginName + '-' + Math.round(Math.random() * 1000000);
                    self.__reloadOptions();
                    
                    self.__instance._on('options.' + self.__namespace, function() {
                        self.__reloadOptions();
                    });
                },
                __destroy: function() {
                    this.__instance._off('.' + self.__namespace);
                },
                __reloadOptions: function() {
                    this.__options = this.__instance._optionsExtract(pluginName, this.__defaults());
                },
                MYPUBLICINSTANCEMETHOD: function(){
                    return this.__instance;
                }
            }
        });
    }));
  3. Create and manage new plugin options

    master

    To add new options, use the instance._optionsExtract protected method. This allows users to provide options either directly or via a namespace.

    Usage Pattern:

    1. Define your default options.
    2. Call instance._optionsExtract(pluginName, defaultOptions) to retrieve the user's configuration.
    3. To handle runtime changes via instance.option(), listen for the options.[namespace] event to reload your settings.

    Example:

    var pluginName = 'namespace.myPlugin';
    
    $.tooltipster._plugin({
        name: pluginName,
        instance: {
            __init: function(instance) {
                var self = this;
                self.__instance = instance;
                self.__namespace = pluginName + '-' + Math.round(Math.random() * 1000000);
                
                self.__reloadOptions();
                
                // Reload options if the user changes them via instance.option()
                self.__instance._on('options.' + self.__namespace, function() {
                    self.__reloadOptions();
                });
            },
            __destroy: function() {
                // Unbind listeners using the unique namespace
                this.__instance._off('.' + self.__namespace);
            },
            __reloadOptions: function() {
                var defaultOptions = {
                    myNewOption: 'value',
                    myNewOption2: 'value'
                };
                this.__myOwnOptions = this.__instance._optionsExtract(pluginName, defaultOptions);
            }
        }
    });
    var pluginName = 'namespace.myPlugin';
    
    $.tooltipster._plugin({
        name: pluginName,
        instance: {
            __init: function(instance) {
                
                var defaultOptions = {
                        myNewOption: 'value',
                        myNewOption2: 'value'
                    },
                    myOwnOptions = instance._optionsExtract(pluginName, defaultOptions);
            }
        }
    });
  4. Namespace CSS for plugins

    master

    To prevent your plugin's CSS from affecting all tooltips on a page, add a unique class to the tooltip root element during __init and use it as a selector in your CSS.

    Implementation:

    __init: function(instance) {
        instance._$tooltip.addClass('tooltipster-myPlugin');
    }

    CSS:

    .tooltipster-myPlugin .tooltipster-content { 
        color: pink; 
    }
  5. Create a Tooltipster plugin

    master

    To create a plugin, use the $.tooltipster._plugin method. You can define logic at the core level (for managing multiple tooltips) or the instance level (for logic specific to a single tooltip).

    Use the following naming conventions for methods:

    • Public: No underscore prefix (e.g., myMethod). Accessible by users.
    • Protected: Single underscore prefix (e.g., _myMethod). Intended for use by other plugins.
    • Private: Double underscore prefix (e.g., __myMethod). Internal to your plugin only.

    Use a namespaced name (e.g., namespace.pluginName) to prevent conflicts with other plugins.

    $.tooltipster._plugin({
        name: 'namespace.pluginName',
        core: {
            __init: function(core) { ... },
            myNewCoreMethod: function() { ... },
            __somePrivateMethod: function() { ... }
        },
        instance: {
            __init: function(instance) { ... },
            __destroy: function() { ... },
            myNewInstanceMethod: function() { ... },
            __somePrivateMethod: function() { ... }
        }
    });
  6. Auto-enable a plugin on all tooltips

    master

    If you want your plugin to be active on all tooltips without requiring users to manually add it to the plugin option, listen to the core init event and manually plug the plugin into the new instance.

    var pluginName = 'namespace.myPlugin'
    
    $.tooltipster._plugin({
        name: pluginName,
        core: {
            __init: function(core) {
                core._on('init', function(event) {
                    event.instance._plug(pluginName);
                });
            }
        }
        instance: {
            // ...
        }
    });
  7. Enable a plugin on tooltips

    master

    To use a custom plugin, include the plugin script in your page after the main Tooltipster script. You must declare the plugin in the plugin option of your tooltip initialization.

    Note: If your plugin is a display plugin (like sideTip), you must include both the display plugin and your custom plugin in the array.

    $('.tooltip').tooltipster({
        plugin: ['sideTip', 'yourPlugin']
    });
  8. Implement `__init` and `__destroy` lifecycle methods

    master

    Tooltipster provides automatic lifecycle hooks:

    • __init:

      • At core level: Called when the plugin is registered.
      • At instance level: Called when a tooltip is initialized (if the plugin is enabled) or manually plugged into an instance.
      • The method receives the core or instance object as its first parameter.
    • __destroy (Instance level only):

      • Called when the tooltip is destroyed or when the plugin is manually unplugged.
      • Use this to perform unbindings and prevent memory leaks.

    Note: Methods are called in the context of your plugin, not the core/instance. You should store a reference to the core/instance to interact with them.

  9. Use Tooltipster Instance Methods

    master

    Once a tooltip instance is created, you can control it directly using instance methods. These methods are called on the specific tooltip instance.

    Methods:

    • close([callback]): Closes the tooltip.
    • content([myNewContent]): Gets or sets the tooltip content.
    • destroy(): Destroys the tooltip instance.
    • disable(): Disables the tooltip.
    • elementOrigin(): Returns the origin element.
    • elementTooltip(): Returns the tooltip element.
    • enable(): Enables the tooltip.
    • instance(): Returns the instance object.
    • on, one, off, triggerHandler: Standard jQuery event methods.
    • open([callback]): Opens the tooltip.
    • option(optionName [, optionValue]): Gets or sets a specific option.
    • reposition(): Repositions the tooltip.
    • status(): Returns the current status.
  10. Use Tooltipster Core Methods

    master

    Core methods allow you to interact with all Tooltipster instances across the entire page or set global defaults.

    Methods:

    • instances([selector || element]): Returns instances matching a selector or element.
    • instancesLatest(): Returns the latest instances.
    • on, one, off, triggerHandler: Global event handling.
    • origins(): Returns the origin elements.
    • setDefaults({}): Sets global default options for all future instances.
  11. Use Tooltipster protected instance methods

    master

    Use these protected methods on the instance object within your plugin logic:

    • _open, _close, _openShortly: Manage tooltip visibility. _open and _close allow passing an event as the first parameter to support new triggers.
    • _on, _one, _off, _trigger: Event management.
    • _optionsExtract: Essential for implementing new plugin options.
    • _plug, _unplug: Manually enable or disable a plugin on an instance.
    • _touch* methods: Handle touch device interactions (e.g., _touchIsTouchEvent).

    Protected Properties:

    • instance._$tooltip: jQuery-wrapped tooltip element.
    • instance._$origin: jQuery-wrapped origin root HTML element.
  12. Configure sideTip Options

    master

    The sideTip plugin is the default plugin for Tooltipster. When using sideTip, you can use the following additional configuration options to control positioning and dimensions:

    • arrow: Show/hide the arrow.
    • distance: Distance from the element.
    • functionPosition: Callback for custom positioning.
    • maxWidth: Maximum width of the tooltip.
    • minIntersection: Minimum intersection required.
    • minWidth: Minimum width of the tooltip.
    • side: Which side of the element to display on.
    • viewportAware: Whether to be aware of the viewport boundaries.