Ensure focus is restored to last active element when nav is closed

This commit is contained in:
2018-04-29 10:57:48 +01:00
parent db70a6cb06
commit 7281d9f94f
2 changed files with 15 additions and 2 deletions

View File

@@ -56,6 +56,7 @@ export default class Navigation {
} }
openNav() { openNav() {
this.lastActiveElement = document.activeElement;
this.state = 'visible'; this.state = 'visible';
this.menu.hideMenu(); this.menu.hideMenu();
this.container.classList.add(STATES.open); this.container.classList.add(STATES.open);
@@ -68,5 +69,8 @@ export default class Navigation {
this.menu.showMenu(); this.menu.showMenu();
this.container.classList.remove(STATES.open); this.container.classList.remove(STATES.open);
this.container.setAttribute('aria-hidden', true); this.container.setAttribute('aria-hidden', true);
if (this.lastActiveElement) {
this.lastActiveElement.focus();
}
} }
} }

View File

@@ -126,12 +126,15 @@ describe('Navigation close button', () => {
describe('Navigation focus behaviour', () => { describe('Navigation focus behaviour', () => {
let first; let first;
let last; let last;
let menu;
beforeEach(() => { beforeEach(() => {
nav.init(); menu = nav.container.querySelector('.Menu');
nav.openNav();
first = nav.container.querySelector('.Nav-link'); first = nav.container.querySelector('.Nav-link');
last = nav.container.querySelector('.Nav-close'); last = nav.container.querySelector('.Nav-close');
menu.focus();
nav.init();
nav.openNav();
}); });
it('Should apply focus to .Nav-titleLink when opened', () => { it('Should apply focus to .Nav-titleLink when opened', () => {
@@ -155,4 +158,10 @@ describe('Navigation focus behaviour', () => {
first.dispatchEvent(event); first.dispatchEvent(event);
expect(document.activeElement).toBe(last); 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);
});
}); });