Merge pull request #3622 from alphagov/searchbox-make-autofocus-optional

Autofocus off by default on live-search
This commit is contained in:
Pea M. Tyczynska
2020-09-29 10:58:00 +01:00
committed by GitHub
14 changed files with 156 additions and 43 deletions

View File

@@ -3,13 +3,26 @@
Modules.Autofocus = function() {
this.start = function(component) {
var forceFocus = $(component).data('forceFocus');
var $component = $(component),
forceFocus = $component.data('forceFocus'),
labelText = $('label[for="' + $component.attr('id') + '"]').eq(0).text().trim(),
clearAriaLabel = evt => {
$component.removeAttr('aria-label');
$component.off('blur', clearAriaLabel);
};
// if the page loads with a scroll position, we can't assume the item to focus onload
// is still where users intend to start
if (($(window).scrollTop() > 0) && !forceFocus) { return; }
$(component).filter('input, textarea, select').eq(0).trigger('focus');
// screenreaders announce the page title when a new page loads
// this will be lost when focus is moved to our form control so add it to the label instead
$component.attr('aria-label', document.title + ' - ' + labelText);
$component.filter('input, textarea, select').eq(0).trigger('focus');
// the page title prefix is only needed on page load so remove once focus has shifted
$component.on('blur', clearAriaLabel);
};
};