From 7281d9f94f5bc310668ae1ab282d00bbeedc3f23 Mon Sep 17 00:00:00 2001 From: Dan Head Date: Sun, 29 Apr 2018 10:57:48 +0100 Subject: [PATCH] Ensure focus is restored to last active element when nav is closed --- js/navigation.js | 4 ++++ js/navigation.spec.js | 13 +++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/js/navigation.js b/js/navigation.js index 5f7f47b..e17cd04 100644 --- a/js/navigation.js +++ b/js/navigation.js @@ -56,6 +56,7 @@ export default class Navigation { } openNav() { + this.lastActiveElement = document.activeElement; this.state = 'visible'; this.menu.hideMenu(); this.container.classList.add(STATES.open); @@ -68,5 +69,8 @@ export default class Navigation { this.menu.showMenu(); this.container.classList.remove(STATES.open); this.container.setAttribute('aria-hidden', true); + if (this.lastActiveElement) { + this.lastActiveElement.focus(); + } } } diff --git a/js/navigation.spec.js b/js/navigation.spec.js index 7287cfd..68559fb 100644 --- a/js/navigation.spec.js +++ b/js/navigation.spec.js @@ -126,12 +126,15 @@ describe('Navigation close button', () => { describe('Navigation focus behaviour', () => { let first; let last; + let menu; beforeEach(() => { - nav.init(); - nav.openNav(); + menu = nav.container.querySelector('.Menu'); first = nav.container.querySelector('.Nav-link'); last = nav.container.querySelector('.Nav-close'); + menu.focus(); + nav.init(); + nav.openNav(); }); it('Should apply focus to .Nav-titleLink when opened', () => { @@ -155,4 +158,10 @@ describe('Navigation focus behaviour', () => { first.dispatchEvent(event); expect(document.activeElement).toBe(last); }); + + test('Focus is restored to last active element when Navigation is closed', () => { + first.focus(); + nav.closeNav(); + expect(document.activeElement).toBe(menu); + }); });