Skip to content

Commit

Permalink
Don’t scroll to legend if input could be obscured
Browse files Browse the repository at this point in the history
Only scroll to the fieldset’s legend (instead of the label associated with the input) if the input would end up in the top half of the screen.

This should avoid situations where the input either ends up off the screen, or obscured by a software keyboard.
  • Loading branch information
36degrees committed Sep 13, 2019
1 parent fec8b91 commit f5efe3c
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/govuk/components/error-summary/error-summary.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ ErrorSummary.prototype.getFragmentFromUrl = function (url) {
*
* Returns the first element that exists from this list:
*
* - The `<legend>` associated with the closest `<fieldset>` ancestor
* - The `<legend>` associated with the closest `<fieldset>` ancestor, as long
* as the top of it is no more than half a viewport height away from the
* bottom of the input
* - The first `<label>` that is associated with the input using for="inputId"
* - The closest parent `<label>`
*
Expand All @@ -109,7 +111,26 @@ ErrorSummary.prototype.getAssociatedLegendOrLabel = function ($input) {
var legends = $fieldset.getElementsByTagName('legend')

if (legends.length) {
return legends[0]
var $candidateLegend = legends[0];

// Only scroll to the fieldset’s legend (instead of the label associated
// with the input) if the input would end up in the top half of the
// screen.
//
// This should avoid situations where the input either ends up off the
// screen, or obscured by a software keyboard.
var legendTop = $candidateLegend.getBoundingClientRect().top
var inputRect = $input.getBoundingClientRect()

// If the browser doesn't support Element.getBoundingClientRect().height
// or window.innerHeight (like IE8), bail and just link to the label.
if (inputRect.height && window.innerHeight) {
var inputBottom = inputRect.top + inputRect.height

if (inputBottom - legendTop < window.innerHeight / 2) {
return $candidateLegend
}
}
}
}

Expand Down

0 comments on commit f5efe3c

Please sign in to comment.