JavaScript
A JavaScript file containing all the Design System's scripts is in the Design System’s npm package at /dist/scripts/design-system.js
.
Including this JavaScript file in your page adds a window.DS
object to the global scope.
Initialise all components
Use initAll()
to initialise all components on the current page.
window.DS.initAll();
You can specify a container element to initialise components within.
This could be useful when you have loaded new content into a section of the page and need to initialise DS components in that section.
window.DS.initAll(document.getElementById('myNewSection'));
The initAll
method will find any elements with a data-module
attribute that corresponds to a Design System component. It will create a new instance of that component and initialise it. For example, this is the markup for a ‘back to top’ component, with its data-module
attribute.
<div class="ds_back-to-top" data-module="ds-back-to-top">
<a href="#" class="ds_back-to-top__button">
Back to top
<svg class="ds_icon ds_back-to-top__icon" aria-hidden="true" role="img">...</svg>
</a>
</div>
initAll()
also initialises the Design System's analytics tracking script. This tracking script adds data attributes to elements that analytics tools can use.
Initialise individual components
The JavaScript classes for each component are in window.DS.components
. Each component class has an init
method that initialises the component.
For example, to set up some new accordions you would:
- select the accordion elements
- create component instances
- initialise the components
const myNewAccordions = [].slice.call(document.querySelectorAll('[data-module="ds-accordion"]'));
myNewAccordions.forEach(accordion =>
new window.DS.components.Accordion(accordion).init()
);
Some Design System components accept more options when instantiated. The documentation page for each component details any available extra options.
Import Design System JavaScript
The Design System uses ES6 modules for its JavaScript. You can import them into your own JavaScript when you need them.
This is an example of importing and using the ‘temporary focus’ helper. You can use ‘temporary focus’ for focus management to aid accessibility.
import temporaryFocus from '/path/to/node_modules/@scottish-government/design-system/src/base/tools/temporary-focus/temporary-focus';
...
temporaryFocus();
Users without JavaScript
We designed Design System components to still be usable without JavaScript. For example, in the character count component, JavaScript is a progressive enhancement. Users without JavaScript see a standard input field with a maxlength
attribute instead.
Feedback, help and support
If you need help or support you can e-mail us at designsystem@gov.scot
There is a problem
Thanks for your feedback