Skip to content

Commit

Permalink
Use CSS to reserve space rather than HTML
Browse files Browse the repository at this point in the history
Use a zero-width space at the end of the content to ensure there's content in the element so that the layout does not shift when JavaScript kicks in
  • Loading branch information
romaricpascal committed Oct 27, 2022
1 parent 65dbd27 commit 20fff96
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
9 changes: 9 additions & 0 deletions src/govuk/components/character-count/_index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@
@include govuk-font($size: false, $tabular: true);
margin-top: 0;
margin-bottom: 0;

&:after {
// Zero-width space that will reserve vertical space when no hint is provided
// as:
// - setting a min-height is not possible without a magic number because the line-height
// is set by the `govuk-font` call above
// - using `:empty` is not possible as the hint macro outputs line breaks
content: "\200B";
}
}

.govuk-character-count__message--disabled {
Expand Down
7 changes: 3 additions & 4 deletions src/govuk/components/character-count/template.njk
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,12 @@
{%- set fallbackHintLength = params.maxwords or params.maxlength %}
{%- set fallbackHintText = params.fallbackHintText or 'You can enter up to %{count} ' + ('words' if params.maxwords else 'characters') %}
{#
Use the fact that `html` has precedence over `text` to override content
when no limit is set and reserve vertical space to avoid layout shifting
by injecting a non-breakable space
If the limit is set in JavaScript, we won't be able to interpolate the message
until JavaScript, so we only set a text if the `maxlength` or `maxwords` options
were provided to the macro.
#}
{{ govukHint({
text: ((fallbackHintText) | replace('%{count}', fallbackHintLength) if not hasNoLimit),
html: (' ' if hasNoLimit),
id: params.id + '-info',
classes: 'govuk-character-count__message' + (' ' + params.countMessage.classes if params.countMessage.classes)
}) }}
Expand Down
2 changes: 1 addition & 1 deletion src/govuk/components/character-count/template.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ describe('Character count', () => {
// and prevent a layout shift when the JavaScript component
// initialises and fills the element with the relevant text
const $countMessage = $('.govuk-character-count__message')
expect($countMessage.html()).toContain(' ')
expect($countMessage.html()).toMatch(/^\s*$/) // Only whitespace
})
})

Expand Down

0 comments on commit 20fff96

Please sign in to comment.