Iconify functions

Iconify is capable of more than just loading and replacing icon placeholders. You can use Iconify in custom scripts to manipulate icons.

Available functions:

Available events:

  • IconifyAddedIcons - this event is triggered when new icons have been loaded from API.
  • IconifyReady - this event is triggered when Iconify has been loaded.

Explanation of each function and event:

Event: IconifyAddedIcons

This event is being called when new icons have been loaded from API. It can be used to wait for icons to load before manipulating those icons.

Sample code that loads several icons then calls callback:

/**
* Load icons
*
* @param {Array} icons List of icons to load
* @param {function} callback Function to call when icons have been loaded
*/

function preloadIconifyIcons(icons, callback) {
  var pending = icons.slice(0),
    loaded = [],
    listener = false;

  /**
   * Check if icons have been loaded
   */

  function check() {
    var stillPending = [];

    // Check if all icons have been loaded
    pending.forEach(function(icon) {
      if (Iconify.iconExists(icon)) {
        loaded.push(icon);
      } else {
        stillPending.push(icon);
      }
    });
    pending = stillPending;

    if (!pending.length) {
      // All icons have been loaded - remove event listener (if it was added) and call callback
      if (listener) {
        document.removeEventListener('IconifyAddedIcons', check);
      }
      callback(loaded);
    }
  }

  // Check if icons have been loaded
  check();
  if (pending.length) {
    // Not all icons are available - setup event listener that
    // calls check() when new icons are added to Iconify storage
    listener = true;
    document.addEventListener('IconifyAddedIcons', check);

    // Load pending icons
    Iconify.preloadImages(pending);
  }
}

/**
* Do your stuff!
*/

preloadIconifyIcons(['mdi:home', 'mdi:arrow-left'], function(icons) {
  // Icons are loaded, do whatever you want!
  console.log('Loaded icons:', icons);
});

Event: IconifyReady

This event is being called when DOM is ready.

It is used internally, use ready() function instead of this event.

Function: preloadImages

Iconify.preloadImages(['fa-home', 'mdi-arrow-left']);

This function loads images from API. It has one argument: array of images to load.

Functions: pauseObserving and resumeObserving

// Pause observer
Iconify.pauseObserving();

// Manipulate DOM without Iconify watching it
// ...

// Resume observer
Iconify.resumeObserving();

These functions pause and resume MutationObserver. What is MutationObserver? It monitors DOM for changes, then tells Iconify that DOM has been changed, so Iconify scans DOM for icon placeholders.

MutationObserver makes it possible to use Iconify in AJAX forms, React applications, Angular applications and any other scripts that change DOM.

If you are doing lots of changes to DOM and don't want Iconify to re-scan DOM, pause scanning by using Iconify.pauseObserving(), then when you are done changing DOM, resume observer using Iconify.resumeObserving();

Most likely you'll never use these functions, but they exist anyway in case if someone needs to temporary disable Iconify.

Functions: getConfig and setConfig

// Get old value
var oldValue = Iconify.getConfig('localStorage');

// Set new value
Iconify.setConfig('localStorage', true);

These functions are used to get and set configuration options.

First argument is option name. In setConfig second argument is new value.

Not all configuration options can be changed after Iconify has been included! getConfig() will return values for all options, but setConfig() can only change several options.

List of options that can be changed at any time (usable with setConfig):

  • defaultAPI - URL of Iconify API, string
  • API - List of custom API URLs for different prefixes. Object, where key is prefix, value is API URL. Setting this option will merge it with existing option rather than overwrite it. See also: Iconify.setCustomAPI()
  • loaderMaxURLSize - Maximum length of API URL, number. It limit is reached when requesting icons from API, request is split into 2 or more requests.
  • sessionStorage - Toggles sessionStorage, boolean. Enabled by default.
  • localStorage - Toggles localStorage, boolean. Disabled by default. If both localStorage and sessionStorage are enabled, both are read on page load, but new icons are stored only in localStorage.
  • SVGAttributes - List of attributes added to SVG, object where key = attribute name, value = attribute value.

List of options that can be changed only before Iconify is included (not usable with setConfig):

  • loaderEvent - Name of DOM event that is triggered when new icons are loaded from API.
  • imageClass - Placeholder class name, string.
  • loadingClass - Pending icon class name that is added to placeholder element when icon is being loaded from API, string.
  • iconAttribute - Name of attribute that stores icon name, string.
  • rotateAttribute - Name of attribute that stores rotation, string.
  • flipAttribute - Name of attribute that stores flip transformation, string.
  • inlineModeAttribute - Name of attribute that stores inline/block mode, string.
  • alignAttribute - Name of attribute that stores alignment, string.
  • appendAttribute - Name of attribute that stores append status (icon is appended to placeholder rather than replaces it), string.
  • appendedClass - Placeholder icon class name that is added to icons when SVG is appended as child node rather than replacing placeholder, string.
  • appendedClass - Placeholder icon class name that is added to icons when SVG is appended as child node rather than replacing placeholder, string.
  • webComponentsPolyfill - URL of web components polyfill for old browsers, string.
  • classListPolyfill - URL of classList polyfill for old browsers, string.

To change options not usable with setConfig you need to create IconifyConfig object before including Iconify:

<script>
  var IconifyConfig = {
    classListPolyfill: '//cdnjs.cloudflare.com/ajax/libs/classlist/1.2.201711092/classList.min.js',
    webComponentsPolyfill: '//cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.24/webcomponents-lite.min.js'
  };
</script>
<script src="//code.iconify.design/1/1.0.0-rc5/iconify.min.js"></script>

Function: setCustomAPI

Iconify.setCustomAPI('prefix', '//my-domain-name.com/{prefix}.js?icons={icons}');

This function sets custom API URL for icons that start with some prefix. First argument is collection prefix, second argument is API URL.

URL can contain several variables:

  • {prefix} - will be replaced with prefix
  • {icons} - will be replaced with list of requested icons

You don't have to host API script if your custom icon set is small. Instead you can upload only .js file that loads all your custom icons and use it as second setCustomAPI argument.

To set custom API URL for all collections, change defaultAPI configuration variable using setConfig function or IconifyConfig object.

Function: addCollection

Iconify.addCollection({
  prefix: 'custom',
  icons: {
    icon1: {
      body: '<path d="..." fill="currentColor" />'
    }
  },
  width: 24,
  height: 24
});

This function adds multiple icons to Iconify storage. It has only one argument: object containing icon data. Format of object is the same as format of JSON collection.

Function: addIcon

Iconify.addIcon('custom-icon2', {
  body: '<path d="..." fill="currentColor" />',
  height: 24,
  width: 24
});

This function adds one icon to Iconify storage.

First argument is icon name, second argument is icon data.

Icon data is an object that contains 1 required key "body" and multiple optional keys.

List of keys:

  • body - SVG content (everything inside svg tag), string.
  • width, height - Icon dimensions, numbers. If not set, icon is assumed to be 16x16.
  • left, top - Left and top offset of viewBox, numbers. If not set, both values are set to 0.
  • rotate - Default rotation. 0 = none, 1 = 90°, 2 = 180°, 3 = 270°. Default value is 0.
  • hFlip, vFlip - Horizontal and vertical flip, boolean. Default value is false.
  • inlineTop, inlineHeight - top and height values when icon is in inline mode. These are usually set for icons imported from glyph fonts. Values default to top and height values.
  • verticalAlign - vertical alignment value when icon is in inline mode. Default value is -0.143 for icons designed for 14px height (such as FontAwesome 4), -0.125 for other icons.

Function: iconExists

if (Iconify.iconExists('some-icon')) {
  // Icon exists in storage! Do something with it
} else {
  // Icon is not in storage, attempt to load it from API
    Iconify.preloadImages(['some-icon']);

  // Here you should subscribe to 'IconifyAddedIcons' event to be notified when icon has been loaded,
  // and check if it has been loaded because event might have been fired for some other icon.

  // Also see: sample code for "IconifyAddedIcons" in this tutorial
}

This function checks if icon has been loaded. Name might be confusing, it is meant as check if icon exists in storage, not if icon exists in API.

Function: listIcons

var icons = Iconify.listIcons();
// icons = ['mdi:home', 'mdi:arrow-left', 'noto:cat', 'emojione:dog'];

var mdiIcons = Iconify.listIcons('mdi');
// mdiIcons = ['home', 'arrow-left'];

This function lists icons that have been loaded.

It has one optional parameter: icon prefix.

If icon prefix is not set, it will return list of all icons with their prefixes. If icon prefix is set, it will return list of icons from specific collection without their prefixes.

Function: getIcon

Iconify.getIcon('icon-name');

This function has only 1 parameter: icon name.

It returns object that contains icon dimensions and body in same format as it is stored in JSON data retrieved from API.

If icon does not exist, it returns null.

Example:

{
  "body": "<path d=\"M1408 768v480q0 26-19 45t-45 19H960V928H704v384H320q-26 0-45-19t-19-45V768q0-1 .5-3t.5-3l575-474 575 474q1 2 1 6zm223-69l-62 74q-8 9-21 11h-3q-13 0-21-7L832 200 140 777q-12 8-24 7-13-2-21-11l-62-74q-8-10-7-23.5T37 654L756 55q32-26 76-26t76 26l244 204V64q0-14 9-23t23-9h192q14 0 23 9t9 23v408l219 182q10 8 11 21.5t-7 23.5z\" fill=\"currentColor\"/>",
  "width": 1664,
  "height": 1312,
  "inlineTop": -224,
  "inlineHeight": 1792,
  "verticalAlign": -0.143,
  "left": 0,
  "top": 0,
  "rotate": 0,
  "vFlip": false,
  "hFlip": false
}

Function: getSVG

var svg1 = Iconify.getSVG('icon-name');
var svg2 = Iconify.getSVG('icon-name', {
  'data-rotate': '90deg',
  'data-height': '32'
});

This function has 2 parameters: icon name and properties. Second parameter is optional.

It returns SVG string (or false if icon does not exist):

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" width="0.93em" height="1em" style="vertical-align: -0.143em;-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);" preserveAspectRatio="xMidYMid meet" viewBox="0 -224 1664 1792"><path d="M1408 768v480q0 26-19 45t-45 19H960V928H704v384H320q-26 0-45-19t-19-45V768q0-1 .5-3t.5-3l575-474 575 474q1 2 1 6zm223-69l-62 74q-8 9-21 11h-3q-13 0-21-7L832 200 140 777q-12 8-24 7-13-2-21-11l-62-74q-8-10-7-23.5T37 654L756 55q32-26 76-26t76 26l244 204V64q0-14 9-23t23-9h192q14 0 23 9t9 23v408l219 182q10 8 11 21.5t-7 23.5z" fill="currentColor"/></svg>

Second parameter for getSVG() is object containing custom properties. It can be used to transform, resize and change color of icon. These are same properties as properties you can add to icon placeholder.

By default getSVG returns data as if icon was in inline mode. To change to block mode add 'data-inline': false to list of custom properties in second parameter.

Function: addFinder

This function is used to create plugins that convert custom placeholders to Iconify icons.

You can find several examples in Iconify plugins repository on GitHub.

First argument is plugin name, second argument is object containing plugin functions and properties.

Function: addTag

// Add <fa-icon> tag that uses "data-icon" attribute for icon name and adds "fa" prefix to it

// <fa-icon data-icon="home" /> is equal to
// <span class="iconify" data-icon-inline="false" data-icon="fa:home" />
Iconify.addTag('fa-icon', false, function(element) {
  var result = element.getAttribute('data-icon');
  return typeof result === 'string' ? 'fa:' + result : '';
});

This function is used to add custom tag. It is intended to be used for plugins. Tag iconify-icon is added using this function.

It has 3 arguments: name of tag (string), default inline state (boolean, can be overwritten with data-inline attribute), function to retrieve icon name from node.

Third argument is optional. If third argument is not set, default function that retrieves icon name from data-icon attribute is used.

Function: ready

Iconify.ready(function() {
  // DOM is ready, do some stuff!
  console.log('DOM is ready!');
});

This function executes code when DOM is ready. If DOM has already been loaded, code is executed on next timer tick.

Function is almost identical to popular jQuery's $(document).ready() function. It is used internally to start scanning document for icons only after entire DOM has been loaded, function was exposed so coders using Iconify could use it as well if they need it.

Function is compatible with all browsers supported by Iconify, including old browsers that don't have DOMContentLoaded event.

Function getVersion

This function returns Iconify version string. It has no arguments.