Iconify SVG framework functions

This article is for outdated Iconify SVG Framework version 1.0.

Documentation for the latest version is available here.

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

Available functions:

Available events:

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-solid: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! Iconify.getConfig() will return values for all options, but Iconify.setConfig() can only change several options.

List of options that can be changed at any time (usable with Iconify.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. If 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 Iconify.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:
           'https://cdnjs.cloudflare.com/ajax/libs/classlist/1.2.201711092/classList.min.js',
       webComponentsPolyfill:
           'https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/0.7.24/webcomponents-lite.min.js',
   };
</script>
<script src="https://code.iconify.design/1/1.0.7/iconify.min.js"></script>

Function: setCustomAPI

Iconify.setCustomAPI(
   'prefix',
   'https://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="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" 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.

See IconifyJSON type.

Function: addIcon

Iconify.addIcon('custom-icon2', {
   body: '<path d="M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z" fill="currentColor"/>',
   height: 24,
   width: 24,
});

This function adds one icon to Iconify storage.

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

See IconifyIcon type.

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,
   "left": 0,
   "top": 0,
   "rotate": 0,
   "vFlip": false,
   "hFlip": false
}

Also see Getting SVG data and IconifyIcon type.

Function: getSVG

var svg1 = Iconify.getSVG('fa-solid:home');
var svg2 = Iconify.getSVG('fa-solid:home', {
   '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"
   focusable="false"
   width="1.13em"
   height="1em"
   style="vertical-align: -0.125em;-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);"
   preserveAspectRatio="xMidYMid meet"
   viewBox="0 0 576 512"
   class="iconify"
   data-icon="fa-solid:home"
>

   <path
       d="M280.37 148.26L96 300.11V464a16 16 0 0 0 16 16l112.06-.29a16 16 0 0 0 15.92-16V368a16 16 0 0 1 16-16h64a16 16 0 0 1 16 16v95.64a16 16 0 0 0 16 16.05L464 480a16 16 0 0 0 16-16V300L295.67 148.26a12.19 12.19 0 0 0-15.3 0zM571.6 251.47L488 182.56V44.05a12 12 0 0 0-12-12h-56a12 12 0 0 0-12 12v72.61L318.47 43a48 48 0 0 0-61 0L4.34 251.47a12 12 0 0 0-1.6 16.9l25.5 31A12 12 0 0 0 45.15 301l235.22-193.74a12.19 12.19 0 0 1 15.3 0L530.9 301a12 12 0 0 0 16.9-1.6l25.5-31a12 12 0 0 0-1.7-16.93z"
       fill="currentColor"
   >
</path>
</svg>

Also see Getting SVG data.

Function: getSVGObject

var icon = Iconify.getSVGObject('fa-solid:home');

This function is similar to getSVG() mentioned above, but instead of returning HTML code, it returns data you can use to render HTML code yourself.

{
   "attributes": {
       "xmlns": "http://www.w3.org/2000/svg",
       "xmlns:xlink": "http://www.w3.org/1999/xlink",
       "aria-hidden": "true",
       "focusable": "false",
       "width": "1em",
       "height": "1em",
       "style": "vertical-align: -0.125em;-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);",
       "preserveAspectRatio": "xMidYMid meet",
       "viewBox": "0 0 24 24"
   },
   "body": "<path d=\"M10 20v-6h4v6h5v-8h3L12 3L2 12h3v8h5z\" fill=\"currentColor\"/>"
}

Result is an object with list of attributes for <svg> and body attribute that has icon content as a string.

Function: addFinder

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

You can find several examples in Iconify v1 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-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: scanDOM

Iconify.scanDOM();

This function immediately scans DOM for changes.

Use it if for some reason you need to scan DOM immediately. For example, if document hasn't finished loading, but you want to replace placeholders.

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 SVG framework version as a string. It has no arguments.

console.log(Iconify.getVersion()); // "1.0.7"