• Stars
    star
    792
  • Rank 55,495 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An autocomplete component, built to be accessible.

Accessible autocomplete

The accessible autocomplete is a component that helps users choose answers from a list you provide. You can also use it to make the answers you get from users more consistent.

If you're asking users to provide their country or territory, the govuk-country-and-territory-autocomplete might be more appropriate.

npm version JavaScript Style Guide gzip size

Sauce Labs Build Status

accessible-autocomplete is a JavaScript autocomplete built from the ground up to be accessible. The design goals are:

  • Accessibility: Following WAI-ARIA best practices and testing with assistive technologies.
  • User experience: Supporting a wide variety of user needs.
  • Compatibility: Working with recommended browsers and assistive technologies.

Try out the examples!


Support

The GOV.UK Design System team maintains the accessible autocomplete as a standalone component. However, we’re only able to put in minimal work to support it.

Read about our plans to maintain this component.

Read more about the types of support we can provide.


Installation / usage

Using npm and a module system

Install it by running:

npm install --save accessible-autocomplete

The accessibleAutocomplete function will render an autocomplete <input> and its accompanying suggestions and aria-live region. Your page should provide a <label> and a container element:

<label for="my-autocomplete">Select your country</label>
<div id="my-autocomplete-container"></div>

Then import it using a module system like Browserify / Webpack / Rollup, and call the accessibleAutocomplete function, providing an array of values:

import accessibleAutocomplete from 'accessible-autocomplete'

const countries = [
  'France',
  'Germany',
  'United Kingdom'
]

accessibleAutocomplete({
  element: document.querySelector('#my-autocomplete-container'),
  id: 'my-autocomplete', // To match it to the existing <label>.
  source: countries
})

If you want to use it as a replacement for a <select> element, read the Progressive enhancement section.

As a plain JavaScript module

You can copy the dist/accessible-autocomplete.min.js file to your JavaScript folder and import it into the browser:

<script type="text/javascript" src="assets/js/accessible-autocomplete.min.js"></script>

Styling the autocomplete

A stylesheet is included with the package at dist/accessible-autocomplete.min.css.

You can copy it to your stylesheets folder and import it into the browser:

<link rel="stylesheet" href="assets/css/accessible-autocomplete.min.css" />

You can also import it using Sass:

@import "accessible-autocomplete";

Using with Preact

If you already use Preact in your application, you can import a bundle that will use that:

import preact from 'preact'
import Autocomplete from 'accessible-autocomplete/preact'

preact.render(
  <Autocomplete id='autocomplete' source={suggest} />,
  document.querySelector('#container')
)

Try out the Preact example!

Using with React

If you already use React in your application, you can import a bundle that will use that:

import React from 'react'
import ReactDOM from 'react-dom'
import Autocomplete from 'accessible-autocomplete/react'

ReactDOM.render(
  <Autocomplete id='autocomplete' source={suggest} />,
  document.querySelector('#container')
)

Try out the React example!

React versions

React v15.5.4 has been tested to work with the Accessible Autocomplete - although make sure to check out documented issues.

React v15.6.2 and 16.0 have been incompletely tested with the Accessible Autocomplete: while no undocumented issues were found, we recommend you carry out thorough testing if you wish to use these or later versions of React.

API documentation

Required options

element

Type: HTMLElement

The container element in which the autocomplete will be rendered in.

id

Type: string

The id to assign to the autocomplete input field, to use with a <label for=id>. Not required if using enhanceSelectElement.

source

Type: Array | Function

An array of values to search when the user types in the input field, or a function to take what the user types and call a callback function with the results to be displayed.

An example of an array of values:

const countries = [
  'France',
  'Germany',
  'United Kingdom'
]

If source is a function, the arguments are: query: string, populateResults: Function

Similar to the source argument for typeahead.js, a backing data source for suggestions. query is what gets typed into the input field, which will callback to populateResults synchronously with the array of string results to display in the menu.

An example of a simple suggestion engine:

function suggest (query, populateResults) {
  const results = [
    'France',
    'Germany',
    'United Kingdom'
  ]
  const filteredResults = results.filter(result => result.indexOf(query) !== -1)
  populateResults(filteredResults)
}

Other options

autoselect (default: false)

Type: Boolean

Set to true to highlight the first option when the user types in something and receives results. Pressing enter will select it.

confirmOnBlur (default: true)

Type: Boolean

The autocomplete will confirm the currently selected option when the user clicks outside of the component. Set to false to disable.

cssNamespace (default: 'autocomplete')

Type: string

Use this property to override the BEM block name that the JavaScript component will use. You will need to rewrite the CSS class names to use your specified block name.

defaultValue (default: '')

Type: string

Specify a string to prefill the autocomplete with.

displayMenu (default: 'inline')

Type: 'inline' | 'overlay'

You can set this property to specify the way the menu should appear, whether inline or as an overlay.

minLength (default: 0)

Type: number

The minimum number of characters that should be entered before the autocomplete will attempt to suggest options. When the query length is under this, the aria status region will also provide helpful text to the user informing them they should type in more.

name (default: 'input-autocomplete')

Type: string

The name for the autocomplete input field, to use with a parent <form>.

onConfirm (default: () => {})

Type: Function

Arguments: confirmed: Object

This function will be called when the user confirms an option, with the option they've confirmed.

placeholder (default: '') ⚠️ not recommended ⚠️

Type: string

This option will populate the placeholder attribute on the input element.

We think placeholders have usability issues and that there are better alternatives to input placeholder text, so we do not recommend using this option.

required (default: false)

Type: Boolean

The input field will be rendered with a required attribute, see W3C required attribute definition.

showAllValues (default: false)

Type: Boolean

If this is set to true, all values are shown when the user clicks the input. This is similar to a default dropdown, so the autocomplete is rendered with a dropdown arrow to convey this behaviour.

showNoOptionsFound (default: true)

Type: Boolean

The autocomplete will display a "No results found" template when there are no results. Set to false to disable.

templates (default: undefined)

Type:

{
  inputValue: Function,
  suggestion: Function
}

This object defines templates (functions) that are used for displaying parts of the autocomplete.

inputValue is a function that receives one argument, the currently selected suggestion. It returns the string value to be inserted into the input.

suggestion is a function that receives one argument, a suggestion to be displayed. It is used when rendering suggestions, and should return a string, which can contain HTML.

⚠️ Caution: because this function allows you to output arbitrary HTML, you should make sure it's trusted, and accessible.

If your template includes child elements with defined foreground or background colours, check they display correctly in forced colors modes. For example, Windows high contrast mode.

dropdownArrow (default: A triangle pointing down)

Type: Function

A function that gets passed an object with the property className ({ className: '' }) and should return a string of HTML or a (P)React element. ⚠️ Caution: because this function allows you to output arbitrary HTML, you should make sure it's trusted, and accessible.

Internationalization

tNoResults (default: () => 'No results found')

Type: Function

A function that receives no arguments and should return the text used in the dropdown to indicate that there are no results.

tStatusQueryTooShort (default: (minQueryLength) => `Type in ${minQueryLength} or more characters for results`)

Type: Function

A function that receives one argument that indicates the minimal amount of characters needed for the dropdown to trigger and should return the text used in the accessibility hint to indicate that the query is too short.

tStatusNoResults (default: () => 'No search results')

Type: Function

A function that receives no arguments and should return the text that is used in the accessibility hint to indicate that there are no results.

tStatusSelectedOption (default: (selectedOption, length, index) => `${selectedOption} ${index + 1} of ${length} is highlighted`)

Type: Function

A function that receives two arguments, the selectedOption and the amount of available options, and it should return the text used in the accessibility hint to indicate which option is selected.

tStatusResults

Default:

(length, contentSelectedOption) => {
  const words = {
    result: (length === 1) ? 'result' : 'results',
    is: (length === 1) ? 'is' : 'are'
  }

  return <span>{length} {words.result} {words.is} available. {contentSelectedOption}</span>
}

Type: Function

A function that receives two arguments, the count of available options and the return value of tStatusSelectedOption, and should return the text used in the accessibility hint to indicate which options are available and which is selected.

tAssistiveHint (default: () => 'When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures.')

Type: Function

A function that receives no arguments and should return the text to be assigned as the aria description of the html input element, via the aria-describedby attribute. This text is intended as an initial instruction to the assistive tech user. The aria-describedby attribute is automatically removed once user input is detected, in order to reduce screen reader verbosity.

Progressive enhancement

If your autocomplete is meant to select from a small list of options (a few hundred), we strongly suggest that you render a <select> menu on the server, and use progressive enhancement.

If you have the following HTML:

<select id="location-picker">
  <option value="fr">France</option>
  <option value="de">Germany</option>
  <option value="gb">United Kingdom</option>
</select>

You can use the accessibleAutocomplete.enhanceSelectElement function to enhance it into an autocomplete:

accessibleAutocomplete.enhanceSelectElement({
  selectElement: document.querySelector('#location-picker')
})

This will:

  • Place an autocomplete input field after the specified <select>
  • Default the autocomplete autoselect to true
  • Default the autocomplete defaultValue to the select's option[selected]
  • Default the autocomplete id to the <select>'s id
  • Default the autocomplete name attribute to '' to prevent it being included in form submissions
  • Default the autocomplete source to use existing <option>s from the <select>
  • Hide the <select> using inline display: none
  • Set the <select>'s id to ${id}-select to decouple from any <label>
  • Upon confirming a value in the autocomplete, update the original <select>

This function takes the same options as accessibleAutocomplete, with the only difference being that it uses selectElement instead of element, which needs to be an instance of HTMLSelectElement.

Note: The accessibleAutocomplete.enhanceSelectElement function is fairly light and wraps the public API for accessibleAutocomplete. If your use case doesn't fit the above defaults, try reading the source and seeing if you can write your own.

Null options

If your <select> element has a "null" option - a default option with no value - then you can pass a defaultValue option to enhanceSelectElement which will replace the label of this option when it is selected.

With the following HTML:

<select id="location-picker">
  <option value="">Select a country</option>
  <option value="fr">France</option>
  <option value="de">Germany</option>
  <option value="gb">United Kingdom</option>
</select>

Then passing a defaultValue option of '' will then leave the autocomplete blank if the null option is selected.

accessibleAutocomplete.enhanceSelectElement({
  defaultValue: '',
  selectElement: document.querySelector('#location-picker')
})

Any null options will also be filtered out of the options used to populate the source of the autocomplete element. To preserve options with no value in the autocomplete, then pass a preserveNullOptions flag of true to enhanceSelectElement.

Analytics and tracking

The following events get triggered on the input element during the life cycle of the autocomplete:

  • onConfirm - This function will be called when the user confirms an option, with the option they've chosen.

Example usage:

accessibleAutocomplete({
  // additional options
  onConfirm: (val) => {
    track(val)
  }
})

Why another autocomplete?

accessible-autocomplete was built after studying many existing solutions and prototyping patches to fix user experience or accessibility issues. It draws heavy inspiration from the following (and a lot of others):

Developing locally

Check out the CONTRIBUTING guide for instructions.

If you want to help and want to get more familiar with the codebase, try starting with the "good for beginners" issues.

License

MIT.

More Repositories

1

govuk-frontend

GOV.UK Frontend contains the code you need to start building a user interface for government platforms and services.
JavaScript
1,108
star
2

whitehall

Publishes government content on GOV.UK
Ruby
833
star
3

govuk-design-system

One place for service teams to find styles, components and patterns for designing government services.
Nunjucks
421
star
4

govuk_frontend_toolkit

❗️GOV.UK Frontend Toolkit is deprecated, and will only receive major bug fixes and security patches.
JavaScript
404
star
5

govuk-aws

The GOV.UK repository for our Migration to AWS
HCL
404
star
6

e-petitions

This is the code base for the UK Government's e-petitions service (https://petition.parliament.uk)
Ruby
301
star
7

govuk-prototype-kit

Rapidly create HTML prototypes of GOV.UK services
JavaScript
293
star
8

govuk_elements

❗️GOV.UK Elements is deprecated, and will only receive major bug fixes and security patches.
HTML
227
star
9

router

HTTP router in front of GOV.UK to proxy to backend servers on a single domain.
Go
205
star
10

government-service-design-manual

Government Service Design Manual
CSS
194
star
11

styleguides

GOV.UK coding standards and guidelines for other tools we use
193
star
12

smart-answers

Serves smart answers on GOV.UK
HTML
168
star
13

magna-charta

Accessible, useful, beautiful barcharts from HTML tables.
JavaScript
152
star
14

unicornherder

Unicorn Herder: manage daemonized (g)unicorns
Python
152
star
15

govuk-puppet

Puppet manifests used to provision remaining parts of the legacy GOV.UK stack (as at Nov 2023: just Licensify left)
Puppet
125
star
16

govuk_template

❗️GOV.UK Template is deprecated, and will only receive major bug fixes and security patches. A template containing the GOV.UK header and footer, and associated assets.
Ruby
110
star
17

gds-way

How we build and operate products at GDS
HTML
92
star
18

govuk-developer-docs

πŸ“– Tech docs for everyone working on GOV.UK
Ruby
92
star
19

govuk-infrastructure

Terraform turnup automation for the EKS Kubernetes clusters that host GOV.UK. See https://github.com/alphagov/govuk-helm-charts for application config.
HCL
91
star
20

wcag-primer

Get up to speed with the Web Content Accessibility Guidelines
HTML
89
star
21

signon

Single sign-on service for GOV.UK
Ruby
87
star
22

govspeak

Markdown extension library for Government editors
Ruby
82
star
23

paas-cf

GOV.UK PaaS - Cloud Foundry
Go
78
star
24

accessibility-tool-audit

Automated accessibility tools audit
HTML
74
star
25

tech-docs-template

A template for building technical documentation with a GOV.UK style
HTML
68
star
26

govuk-guix

Package, service and system definitions using GNU Guix for software and systems related to GOV.UK.
Scheme
63
star
27

govuk_frontend_alpha

This repository will be archived.
CSS
61
star
28

notifications-api

GOV.UK Notify API
Python
60
star
29

govuk_publishing_components

A gem to document and distribute frontend components for GOV.UK applications
JavaScript
59
star
30

Product-Managers-Learn-By-Doing

Things you should know how to do, to be a successful Product Manager
59
star
31

govuk-docker

GOV.UK development environment using Docker 🐳
Ruby
59
star
32

design-principles

Serves /design-principles on GOV.UK
HTML
57
star
33

fabric-scripts

DEPRECATED
Python
57
star
34

govuk-rfcs

GOV.UK staff use this repository as a forum to discuss and make technical decisions
55
star
35

cdn-acceptance-tests

CDN Acceptance Tests
Go
49
star
36

terraform-provider-concourse

A terraform provider for Concourse
Go
48
star
37

calendars

Serves /bank-holidays and /when-do-the-clocks-change on GOV.UK
Ruby
47
star
38

government-frontend

Serves government pages on GOV.UK
Ruby
46
star
39

publisher

Publishes mainstream content on GOV.UK
Ruby
42
star
40

smokey

Smoke tests for GOV.UK
Ruby
41
star
41

pay-publicapi

The Payments Public API in Java (Dropwizard)
Java
40
star
42

puppet-auditd

Puppet module for Auditd
Ruby
39
star
43

fourth-wall

Retired pull request and build status monitor
JavaScript
38
star
44

notifications-admin

GOV.UK Notify frontend application
Python
37
star
45

paas-alpha-tsuru-terraform

HCL
36
star
46

spotlight

Hybrid rendering application for the Performance Platform using Backbone and D3
JavaScript
36
star
47

need-o-tron

Ruby
35
star
48

paas-docker-cloudfoundry-tools

Ruby
34
star
49

govuk-country-and-territory-autocomplete

An autocomplete widget that uses data from Country and Territory Register.
JavaScript
33
star
50

puppet-aptly

Puppet module for aptly
Ruby
33
star
51

collections

Serves GOV.UK navigation pages, browse, topic, step-by-steps & services and information pages.
Ruby
33
star
52

govuk-coronavirus-vulnerable-people-form

Helps the public get support during the COVID-19 pandemic
Ruby
33
star
53

gsp

GSP is a container platform and curated suite of components helping government deploy, run, observe and secure their services
Go
31
star
54

slimmer

Templating Rack middleware, injects standard header/footer and GOV.UK Components
Ruby
30
star
55

content-publisher

Publishing application for GOV.UK
Ruby
29
star
56

publishing-api

API to publish content on GOV.UK
Ruby
29
star
57

frontend

Serves the homepage, transactions and some index pages on GOV.UK
Ruby
29
star
58

puppet-skeleton

Skeleton project for infrastructure teams
Ruby
27
star
59

gds-boxen

Apple Macbook setup via Puppet - forked from https://github.com/boxen/our-boxen
Puppet
26
star
60

govuk-content-schemas

Definitions of the data formats used to represent content on GOV.UK
Jsonnet
26
star
61

data-ethics-and-society-reading-group

Data ethics and society reading group for cross government sessions on books and articles relating to ethics in data science
25
star
62

prototyping

Old tool for making prototypes. No longer maintained. Use https://github.com/alphagov/govuk_prototype_kit instead
HTML
25
star
63

search-api

Search API for GOV.UK
Ruby
25
star
64

accessibility-personas

Experience the web as personas with access needs
HTML
24
star
65

data-standards-authority

Collaboration space for working on data standards and guidance for the DSA
JavaScript
24
star
66

content-store

API for content on GOV.UK
Ruby
23
star
67

prometheus-aws-configuration-beta

Terraform configuration to manage a Prometheus server running on AWS.
HCL
23
star
68

paas-alpha-tsuru-ansible

Ansible configs for Tsuru
Python
23
star
69

gds-sso

OmniAuth adapter to allow apps to sign in via GOV.UK signon
Ruby
23
star
70

govuk-frontend-docs

Technical documentation for GOV.UK Frontend
HTML
22
star
71

govuk_frontend_toolkit_gem

A gem wrapper around the govuk_frontend_toolkit files to enable easy integration with Rails
Ruby
22
star
72

govuk-taxonomy-supervised-learning

Auto-tag govuk content to the collated legacy taxonomies
Jupyter Notebook
21
star
73

accessibility-community-notes-and-discussion

Draft accessibility guidance
21
star
74

alphagov.github.io

GitHub organisation site for GDS. Also an Apache Maven repository.
HTML
21
star
75

paas-billing

A Go application for generating billing data from cloudfoundry events
Go
21
star
76

interaction-diagrams

Tooling to generate microservice interaction diagrams using wireshark and PCAP processing.
Ruby
20
star
77

government-digital-strategy

Government Digital Strategy
CSS
20
star
78

govuk-browser-extension

Chrome and Firefox extension for developers working on GOV.UK.
JavaScript
20
star
79

verify-frontend

The frontend service for GOV.UK Verify
Ruby
20
star
80

release

Helps deploying to GOV.UK
Ruby
20
star
81

table-editor

Table editor for creating complex tables in HTML
HTML
19
star
82

pay-selfservice

Payments Team Self Service
JavaScript
19
star
83

fastly-configure

Configures GOV.UK Fastly setup via the command-line
Ruby
19
star
84

govuk-related-links-recommender

Machine learning model to recommend related content
Python
19
star
85

govuk_admin_template

[Deprecated] Styles, scripts and templates for building GOV.UK backend admin apps
JavaScript
19
star
86

govuk-terraform-provisioning

**DEPRECATED** Terraform configuration and utilities to provision parts of the GOV.UK AWS Infrastructure
HCL
19
star
87

static

GOV.UK static files and resources
JavaScript
18
star
88

notifications-net-client

.NET client for the GOV.UK Notify API
C#
18
star
89

gds-nodejs-boilerplate

A Node.js project boilerplate for production apps
JavaScript
18
star
90

paas-cf-conduit

Go
18
star
91

backdrop

Storing and querying data for the Performance Platform
Python
18
star
92

datainsight-frontend

Public facing web app to display various measurements of the GOV.UK site
JavaScript
18
star
93

govuk-archive

18
star
94

aws-security-alarms

CloudTrail and CloudWatch configuration with some basic security alarms.
HCL
18
star
95

govuk-lda-tagger

An experiment of using the LDA machine learning algorithm to generate topics from documents and tag them with those topics
Jupyter Notebook
17
star
96

panopticon

Retired. App that holds some of the content on GOV.UK
Ruby
17
star
97

seal

Slack bot that publishes a team's pull requests to their Slack channel
Ruby
17
star
98

verify-service-provider

πŸ‘‘ β˜‘οΈ The easiest way to connect to GOV.UK Verify
Java
17
star
99

paas-aiven-broker

A service broker to provide Aiven Elasticsearch and InfluxDB services to Cloud Foundry users
Go
17
star
100

finder-frontend

Serves finder and search pages for GOV.UK
Ruby
17
star