diff --git a/app/assets/javascripts/autofocus.js b/app/assets/javascripts/autofocus.js index 97267b32e..b688a9f20 100644 --- a/app/assets/javascripts/autofocus.js +++ b/app/assets/javascripts/autofocus.js @@ -10,7 +10,16 @@ // is still where users intend to start if (($(window).scrollTop() > 0) && !forceFocus) { return; } - $component.filter('input, textarea, select').eq(0).trigger('focus'); + // See if the component itself is something we want to send focus to + var target = $component.filter('input, textarea, select'); + + // Otherwise look inside the component to see if there are any elements + // we want to send focus to + if (target.length === 0) { + target = $('input, textarea, select', $component); + } + + target.eq(0).trigger('focus'); }; }; diff --git a/tests/javascripts/autofocus.test.js b/tests/javascripts/autofocus.test.js index 04b207ca5..3617ca1d9 100644 --- a/tests/javascripts/autofocus.test.js +++ b/tests/javascripts/autofocus.test.js @@ -20,7 +20,7 @@ describe('Autofocus', () => { // set up DOM document.body.innerHTML = - `
+ `
@@ -50,6 +50,18 @@ describe('Autofocus', () => { }); + test('is focused when attribute is set on outer element', () => { + + document.getElementById('search').removeAttribute('data-module'); + document.getElementById('wrapper').setAttribute('data-module', 'autofocus'); + + // start module + window.GOVUK.modules.start(); + + expect(focusHandler).toHaveBeenCalled(); + + }); + test('is not focused if the window has scrolled', () => { // mock the window being scrolled 25px