Skip to content

JavaScript Utilities

In Util.js, we provide a set of JavaScript utilities. These utilities are designed to help with common tasks such as DOM manipulation, adding/removing classes and event handling.

Initialization

Util.init() is included in Patternlab.init() and is automatically called when the PatternLab instance is initialized.

toggleVisibility()

Toggle Visibility of an element by adding or removing a class. This will toggle between h-hide and h-show helper classes.

  • If the element has h-hide class, it will be shown.
  • If the element has h-show class, it will be hidden.
javascript
Util.toggleVisibility(nodeElement);

hide()

Hide an element by adding the h-hide class.

javascript
Util.hide(nodeElement);

show()

Show an element by adding the h-show class.

javascript
Util.show(nodeElement);

getHeight()

Useful to get the height of an element that is not visible.

javascript
Util.getHeight(nodeElement);

setClass()

Set a Class for all elements in a NodeList.

  • els: The NodeList of elements to which the class will be added.
  • className: The class name that should be set.
  • fnName: The classList method name (add, remove, toggle..).
javascript
Util.setClass(els, className, fnName);

toggleStickyClass()

Add a sticky class to an element when it reaches a certain position in the viewport.

  • element: The DOM element to which the sticky class will be added.
  • className: The class name to be added when the element becomes sticky: default is -is-sticky.
  • offset: The vertical offset in pixels from the top of the viewport at which the class will be added.
javascript
Util.toggleStickyClass(element, className, offset);

Example Usage

javascript
Util.toggleStickyClass(document.querySelector('.header'), '-is-sticky', 100);

ready()

Wait for the DOM to fully load before e.g. attaching events to objects in the DOM. Replaces to jQuery's $(document).ready().

javascript
Util.ready(fn);