alphagov / govuk-frontend

GOV.UK Frontend contains the code you need to start building a user interface for government platforms and services.
https://frontend.design-system.service.gov.uk/
MIT License
1.16k stars 320 forks source link

Hard-coded id for character count component #1766

Open Dawdre opened 4 years ago

Dawdre commented 4 years ago

this.$countMessage = $module.querySelector('[id=' + this.$textarea.id + '-info]')

Hey! Currently trying to implement your character count component. I am not using Nunjucks, so relying on copying the HTML from your examples (https://design-system.service.gov.uk/components/character-count/). On further investigation as to why it was not working, even though my DOM was identical (or at least I though it was). The above snippet hard-codes -info onto the end of the span id (from character-count.js).

Nowhere does this appear to be documented (if it is, and I have missed this, accept my apologies and close this immediately)? It does seem somewhat brittle? Your own govuk-frontend version here https://github.com/alphagov/govuk-frontend/blob/master/src/govuk/components/character-count/template.njk also manually adds -info onto the hint.

Now whilst calling the Nunjucks macro would always works and you don't need to care that this behaviour is happening behind the scenes. Anyone using raw HTML or implementing it into another templating language, is bound to run into this issue? The example code snippets on your component pages seem to be mostly contrived names/ids so one would quite easily rely on that not being a hard and fast rule to make the component work.

I have mine all working now, so not a major problem for me anymore but thought I would ask the question.

Thanks

NickColley commented 4 years ago

Heya @Dawdre,

The important thing in the HTML is that the textarea is associated with the count message, we use the aria-describedby attribute which references the count message's id attribute.

We could consider changing the logic so that we take advantage of that relationship, which would allow you to use any id you want on the count message, as long as you also create the correct association with the textarea using aria-describedby.

I have created a pull request to demonstrate this, would be interested in your thoughts:

https://github.com/alphagov/govuk-frontend/pull/1767/files

Update: Looks like my proposal wouldnt work as I thought.