Themes

Demonstration
Code

The Theme toggle provides users with the ability to toggle through a predefined set of high-contrast themes, light or dark. Themes are based on the Opportunity Standard color system.


Theme toggling is a new inclusive design pattern for many users. It is recommended to display the interface in the light theme first and allow them to select the dark theme based on their preference.


The theme toggling element should be placed consistently with other global site features such as languages or search, however, it is a lower priority to the languages select element.


Theme colors should be consistent between elements in the interface, using the theme scale defined by the color system. Toggling alternatively colored modals or brightly colored elements can be visually jarring for users with certain color sensitivities.

Global Script

The Theme toggle requires JavaScript for functionality. It uses the Patterns Scripts, Theme Utility to cycle through themes and setting the users preference to local storage. To use the Theme through the global script use the following code:

<script src="@nycopportunity/standard/dist/js/default.js"></script>

<script>
  var Standard = new Default();

  Standard.themes();
</script>

This will instantiate the Theme toggling element and attach event listeners to the body.

Module Import

The Theme Utility source exists in the Patterns Scripts utility library, which is a dependency of this library. This method allows the specification of each theme object and a callback function that will be triggered after the theme is toggled.

import Themes from '@nycopportunity/pttrn-scripts/src/themes/themes';

new Themes({
  themes: [
    {
      label: 'Dark Theme',
      classname: 'default',
      icon: 'lucide-moon'
    },
    {
      label: 'Light Theme',
      classname: 'dark',
      icon: 'lucide-sun'
    }
  ],
  after: thms => document.querySelectorAll(thms.selectors.TOGGLE)
    .forEach(element => {
      element.querySelector('[data-js-themes="icon"]')
        .setAttribute('href', `#${thms.theme.icon}`);
    })
});