Skip to content

Commit

Permalink
Merge pull request #2450 from alphagov/focus-skiplink-target
Browse files Browse the repository at this point in the history
Set focus to skip link target to improve screen reader announcements
  • Loading branch information
hannalaakso authored Dec 7, 2021
2 parents 873cc06 + 907a0cc commit caa729c
Show file tree
Hide file tree
Showing 10 changed files with 199 additions and 1 deletion.
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,24 @@ You do not need to do anything if you're using Nunjucks macros.

This change was introduced in [pull request #2437: Remove `display:block` on hint component](https://github.com/alphagov/govuk-frontend/pull/2437).

#### Include JavaScript for skip link to improve screen reader announcements

We've added JavaScript for the skip link component to set focus to the linked element, for example, the main content on the page. This helps screen readers read the linked content when users use the skip link.

If you're not using Nunjucks macros, add a `data-module="govuk-skip-link"` attribute to the component HTML. For example:

```html
<div class="govuk-skip-link" data-module="govuk-skip-link">
...
</div>
```

If you're [importing JavaScript for individual components](https://frontend.design-system.service.gov.uk/importing-css-assets-and-javascript/#select-and-initialise-an-individual-component), import the skip link JavaScript.

Once you've made the changes, check that the skip link JavaScript works. To make sure, click the skip link and check that the linked element (usually the `<main>` element) in the browser has a `tabindex` attribute.

This change was introduced in [pull request #2450: Set focus to skip link target to improve screen reader announcements](https://github.com/alphagov/govuk-frontend/pull/2450).

#### Remove calls to deprecated `iff` Sass function

We've removed the `iff` function which we deprecated in [GOV.UK Frontend version 3.6.0](https://github.com/alphagov/govuk-frontend/releases/tag/v3.6.0).
Expand Down
1 change: 1 addition & 0 deletions app/views/examples/template-custom/index.njk
Original file line number Diff line number Diff line change
Expand Up @@ -130,5 +130,6 @@
{% block bodyEnd %}
<!-- block:bodyEnd -->
<script src="/public/all.js"></script>
<script>window.GOVUKFrontend.initAll()</script>
<!-- endblock:bodyEnd -->
{% endblock %}
8 changes: 8 additions & 0 deletions app/views/examples/template-default/index.njk
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,14 @@
<![endif]-->
{% endblock %}

{% block content %}
<!-- block:content -->
<h1 class="govuk-heading-xl">Default page template</h1>
<!-- endblock:content -->
{% endblock %}


{% block bodyEnd %}
<script src="/public/all.js"></script>
<script>window.GOVUKFrontend.initAll()</script>
{% endblock %}
6 changes: 6 additions & 0 deletions src/govuk/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ErrorSummary from './components/error-summary/error-summary'
import NotificationBanner from './components/notification-banner/notification-banner'
import Header from './components/header/header'
import Radios from './components/radios/radios'
import SkipLink from './components/skip-link/skip-link'
import Tabs from './components/tabs/tabs'

function initAll (options) {
Expand Down Expand Up @@ -61,6 +62,10 @@ function initAll (options) {
new Radios($radio).init()
})

// Find first skip link module to enhance.
var $skipLink = scope.querySelector('[data-module="govuk-skip-link"]')
new SkipLink($skipLink).init()

var $tabs = scope.querySelectorAll('[data-module="govuk-tabs"]')
nodeListForEach($tabs, function ($tabs) {
new Tabs($tabs).init()
Expand All @@ -77,5 +82,6 @@ export {
ErrorSummary,
Header,
Radios,
SkipLink,
Tabs
}
1 change: 1 addition & 0 deletions src/govuk/all.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ describe('GOV.UK Frontend', () => {
'ErrorSummary',
'Header',
'Radios',
'SkipLink',
'Tabs'
])
})
Expand Down
13 changes: 13 additions & 0 deletions src/govuk/components/skip-link/_index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,17 @@
}
}
}

.govuk-skip-link-focused-element {
&:focus {
// Remove the native visible focus indicator when the element is programmatically focused.
//
// We set the focus on the linked element (this is usually the <main> element) when the skip
// link is activated to improve screen reader announcements. However, we remove the visible
// focus indicator from the linked element because the user cannot interact with it.
//
// A related discussion: https://github.com/w3c/wcag/issues/1001
outline: none;
}
}
}
93 changes: 93 additions & 0 deletions src/govuk/components/skip-link/skip-link.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import '../../vendor/polyfills/Function/prototype/bind'
import '../../vendor/polyfills/Element/prototype/classList'
import '../../vendor/polyfills/Event' // addEventListener and event.target normalization

function SkipLink ($module) {
this.$module = $module
}

/**
* Initialise the component
*/
SkipLink.prototype.init = function () {
var $module = this.$module
// Check for module
if (!$module) {
return
}

$module.addEventListener('click', this.handleClick.bind(this))
}

/**
* Click event handler
*
* @param {MouseEvent} event - Click event
*/
SkipLink.prototype.handleClick = function (event) {
var target = event.target

if (this.focusLinkedElement(target)) {
event.preventDefault()
}
}

/**
* Focus the linked element
*
* @param {HTMLElement} $target - Event target
* @returns {boolean} True if the linked element was able to be focussed
*/
SkipLink.prototype.focusLinkedElement = function ($target) {
// If the element that was clicked does not have a href, return early
if ($target.href === false) {
return false
}

var linkedElementId = this.getFragmentFromUrl($target.href)
var $linkedElement = document.getElementById(linkedElementId)
if (!$linkedElement) {
return false
}

if (!$linkedElement.getAttribute('tabindex')) {
// Set the content tabindex to -1 so it can be focused with JavaScript.
$linkedElement.setAttribute('tabindex', '-1')
$linkedElement.classList.add('govuk-skip-link-focused-element')

$linkedElement.addEventListener('blur', this.removeFocusProperties.bind(this, $linkedElement))
}
$linkedElement.focus()
}

/**
* Remove the tabindex that makes the linked element focusable because the content only needs to be
* focusable until it has received programmatic focus and a screen reader has announced it.
*
* Remove the CSS class that removes the native focus styles.
*
* @param {HTMLElement} $linkedElement - DOM element linked to from the skip link
*/
SkipLink.prototype.removeFocusProperties = function ($linkedElement) {
$linkedElement.removeAttribute('tabindex')
$linkedElement.classList.remove('govuk-skip-link-focused-element')
}

/**
* Get fragment from URL
*
* Extract the fragment (everything after the hash) from a URL, but not including
* the hash.
*
* @param {string} url - URL
* @returns {string} Fragment from URL, without the hash
*/
SkipLink.prototype.getFragmentFromUrl = function (url) {
if (url.indexOf('#') === -1) {
return false
}

return url.split('#').pop()
}

export default SkipLink
50 changes: 50 additions & 0 deletions src/govuk/components/skip-link/skip-link.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/* eslint-env jest */

const configPaths = require('../../../../config/paths.json')
const PORT = configPaths.ports.test

const baseUrl = 'http://localhost:' + PORT

describe('/examples/template-default', () => {
describe('skip link', () => {
beforeAll(async () => {
await page.goto(`${baseUrl}/examples/template-default`, { waitUntil: 'load' })
await page.keyboard.press('Tab')
await page.keyboard.press('Enter')
})

it('focuses the linked element', async () => {
const activeElement = await page.evaluate(() => document.activeElement.id)

expect(activeElement).toBe('main-content')
})

it('adds the tabindex attribute to the linked element', async () => {
const tabindex = await page.$eval('.govuk-main-wrapper', el => el.getAttribute('tabindex'))

expect(tabindex).toBe('-1')
})

it('adds the class for removing the native focus style to the linked element', async () => {
const cssClass = await page.$eval('.govuk-main-wrapper', el => el.classList.contains('govuk-skip-link-focused-element'))

expect(cssClass).toBeTruthy()
})

it('removes the tabindex attribute from the linked element on blur', async () => {
await page.$eval('.govuk-main-wrapper', el => el.blur())

const tabindex = await page.$eval('.govuk-main-wrapper', el => el.getAttribute('tabindex'))

expect(tabindex).toBeNull()
})

it('removes the class for removing the native focus style from the linked element on blur', async () => {
await page.$eval('.govuk-main-wrapper', el => el.blur())

const cssClass = await page.$eval('.govuk-main-wrapper', el => el.getAttribute('class'))

expect(cssClass).not.toContain('govuk-skip-link-focused-element')
})
})
})
2 changes: 1 addition & 1 deletion src/govuk/components/skip-link/template.njk
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<a href="{{ params.href | default('#content') }}" class="govuk-skip-link{%- if params.classes %} {{ params.classes }}{% endif -%}"{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}"{% endfor %}>
<a href="{{ params.href | default('#content') }}" class="govuk-skip-link{%- if params.classes %} {{ params.classes }}{% endif -%}"{%- for attribute, value in params.attributes %} {{ attribute }}="{{ value }}"{% endfor %} data-module="govuk-skip-link">
{{- params.html | safe if params.html else params.text -}}
</a>
8 changes: 8 additions & 0 deletions src/govuk/components/skip-link/template.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,5 +76,13 @@ describe('Skip link', () => {
expect($component.attr('data-test')).toEqual('attribute')
expect($component.attr('aria-label')).toEqual('Skip to content')
})

it('renders a data-module attribute to initialise JavaScript', () => {
const $ = render('skip-link', examples.default)

const $component = $('.govuk-skip-link')

expect($component.attr('data-module')).toEqual('govuk-skip-link')
})
})
})

0 comments on commit caa729c

Please sign in to comment.