How to guides Setting up JavaScript

Several MOJ Pattern Library components use JavaScript to provide interactive features. In order to fully use these components you will need to add some code to your service to set up the JavaScript.

You can either

  • include the MOJ Pattern Library's JavaScript code directly in your HTML templates
  • import the JavaScript using a bundler like Webpack

Add the JavaScript file to your HTML

To include the code directly in a template, first either:

  • set up your routing so that requests for the JavaScript file are served from node_modules/@ministryofjustice/frontend/moj/all.js
  • copy the node_modules/@ministryofjustice/frontend/moj/all.js file into your application

You will also need to install and serve jQuery.

Then import the JavaScript file before the closing </body> tag of your HTML page or page template, and run the initAll function to initialise the components.

  <script src="<YOUR-APP>/jquery.js"></script>
  <script src="<YOUR-APP>/<YOUR-JS-FILE>.js"></script>

Some components cannot be initialised by this method and this is noted on their individual documentation pages. For more details, see below.

Import using a bundler

If you decide to import using a bundler, use import to import jQuery and all of the design systems’s components, then run the initAll function to initialise them:

import $ from 'jquery'
import { initAll } from '@ministryofjustice/frontend'

window.$ = $

Initialize individual components

Rather than using initAll, you can initialise individual components by identifying them with their data-module attribute. For example, to initialise just the Password reveal component:

var PasswordReveal = window.MOJFrontend.PasswordReveal
var $passwordReveal = document.querySelector('[data-module="moj-password-reveal"]')
if ($passwordReveal) {
    new PasswordReveal($passwordReveal)

This approach is necessary for the following components because they require manual configuration. There is more detail on each of their documentation pages: