Using JavaScript functions

Our themes and extensions are built on top of a powerful set of JavaScript utility functions which you can take advantage of when writing custom code.

The JavaScript files used by our themes are contained within each theme’s Assets folder:

theme/
├── assets/
│  ├── extensions.js
│  ├── extension-article-navigation.js
│  ├── ...
│  ├── page-request.js
│  ├── page-requests.js
│  └── util.js
│  └── widgets.js
└── script.js

The script.js in the theme’s root directory contains general JavaScript functionality for simple functionality like social share links.

The JavaScript files within the assets/ folder are described in the sections below.

Extensions

Additional JavaScript functionality can be added through our range of extensions. All of our extensions are included for free with every theme, but need to be referenced in the footer.hbs template to be used. For example, to use the System Status extension you’d first add a reference to the JavaScript file within the theme’s Assets folder:

<script type="text/javascript" defer src="{{asset 'extension-system-status.js'}}"></script>

For more information about how to install and use extensions, refer to usage instructions on each extensions’s page.

The extensions.js file includes the Collapse, Tabs, Toggles, Carousels, Table of Contents, Sticky and Scrollspy extensions.

Utilities

The util.js file contains all of the JavaScript functions required by our themes and extensions. A reference to it is contained within the document_head.hbs template and should not be removed.

A minified version is used by default for performance reasons, but we recommend that you review the util.js source file to learn more about the complete set of available functions used in our themes. Each function is accompanied by a full comment block description outlining its purpose and parameters.

The most commonly-used utility functions are described below.

ready

ready(callback)

Executes the given callback function when the page is ready.

ready(function() {
  // Do something when the page is ready
});

If ready() is called after the page is ready, the callback function will be executed immediately.

each

each(selector, callback)

Executes the given callback function once for each DOM element matched by the selector.

each('ul > li', function(el) {
  // Do something with the list item
});

closest

Util.closest(el, selector)

Returns the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

var navLink = document.querySelector('.nav-link');
var nav = Util.closest(navLink, '.nav');

get

Util.get(objectTypes, [properties])

Returns objects from the Zendesk REST API using a cached fetch request.

Util.get(['categories', 'sections', 'articles']).then(function(collection) {
  // Do something with the collection of objects
});

The following object types are supported:

  • categories
  • sections
  • articles
  • topics
  • posts

If you specify one or more object properties in the second optional properties parameter, only those properties will be returned. Objects and their properties are described in Zendesk’s REST API documentation.

The collection object returned in the callback function contains an array of objects for each of the object types specified. All responses are cached using sessionStorage for performance reasons.

replaceWithSVG

Util.replaceWithSVG(els)

Replaces one or more images with inline SVGs. The function accepts a DOM element, NodeList or selector string as an argument.

Class names and attributes from the original element will be copied across. You can therefore add any required utility classes (e.g., .fill-current) to the original element in your template.

// Using a selector
Util.replaceWithSVG('.svg-icon');

// Using a DOM element
var img = document.querySelector('.svg-icon');
Util.replaceWithSVG(img);

Alternatively you can use the data-inline-svg attribute to automatically apply this method to the element.

<img src="category.svg" alt="..." data-inline-svg>

onTransitionEnd

Util.onTransitionEnd(el, callback)

Invokes a callback function when the transition effect on a given element has ended. If there is no defined transition duration on the given element the callback function will be called immediately.

var el = document.getElementById('an-element');

Util.onTransitionEnd(el, function() {
  // Do something when the transition ends
});

el.classList.add('opacity-0');

debounce

Util.debounce(function, wait, [immediate])

Creates and returns a new debounced version of the passed function which will postpone its execution until a certain number of milliseconds have elapsed since the last time it was invoked. At the end of the wait interval, the function will be called with the arguments that were most recently passed to the debounced function.

var onScroll = Util.debounce(function(e) {
  // Do something on scroll
}, 200);

window.addEventListener('scroll', onScroll);

Pass true for the immediate argument to cause debounce to trigger the function on the leading instead of the trailing edge of the wait interval. This could be used, for example, to prevent accidental double-clicks on a “submit” button from firing a second time.

template

Util.template(templateString, [settings])

Compiles a template string into a function that can then be rendered using template data.

Template strings can both interpolate values using <%= … %> as well as execute arbitrary JavaScript code with <% … %>.

var templateString = "<h1><%= heading %></h1><p><%= body %></p>";
var templateData = { heading: "This is a heading", body: "This is the body" };
var template = Util.template(templateString);
var html = template(templateData);

renderTemplate

Util.renderTemplate(el, templateId, data)

Renders a custom template within the given element using arbitrary data. Useful for rendering complicated bits of HTML from JSON data sources.

For more information, refer to our article on using micro-templating.

Widgets

The widgets.js file contains a set of bundled Alpine.js functionality that we call widgets. Widgets allow you to quicky and easily add new functionality into otherwise static HTML.

For example, you can extend a simple set of toggles built using our Collapse extension using the Toggles widget to update individual toggle colors and icons when a visitor interacts with them:

Toggles using Alpine JS and our Collapse extension

Alpine JS also useful when using micro-templates, as it can respond to native browser events as well as those emitted by our extensions.

Other examples of widgets include the popular search terms on the Home page and dropdown menus used throughout the help center.

Page-specific scripts

Functionality specific to the Request and Requests pages are contained within the page-request.js and page-requests.js files, respectively.

Each is referenced on the page template itself, for example:

<script type="text/javascript" defer src="{{asset 'page-request.js'}}"></script>

Each page also has an inline script that adds one or more class names to the document body, which you can use when writing page-specific CSS:

<script type="text/javascript">
  document.documentElement.classList.add('article-page', 'article-' + {{article.id}})
</script>

Questions or feedback about this article? Let us know