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

Allow pre-selecting a specific tab when using the tabs component #3065

Open 36degrees opened 1 year ago

36degrees commented 1 year ago

Related component

Tabs

Context

Unless you pass the ID for a specific tab as part of the anchor in the URL, the tabs component assumes that you always want the first tab to be visible:

https://github.com/alphagov/govuk-frontend/blob/19015c3df291db1653ea94793bfcbd95cbdd4063/src/govuk/components/tabs/tabs.mjs#L76-L78

If you're using the Nunjucks macro, the --selected modifier is always added to the first tab:

https://github.com/alphagov/govuk-frontend/blob/19015c3df291db1653ea94793bfcbd95cbdd4063/src/govuk/components/tabs/template.njk#L14

However, if the user is using the HTML they can put the --selected modifier on whichever tab they like – but because of the assumption in the JavaScript, the tab to be visible on page load, but as soon as the JavaScript kicks the user will be switched back to the first tab.

I'd suggest:

Alternatives

One alternative is to include the ID of the target tab in the URL when linking to the page, but that results in the viewport being scrolled to the top of the tab, cutting off the top of the page.

Additional information (if applicable)

This came up when supporting a user on Slack, who (quite rightly) expected to be able to set the active tab by moving the --selected modifier class, and was surprised when that didn't work.

querkmachine commented 1 year ago

Is there any benefit to defining the default based on the presence of a modifier class versus using a data-* attribute or JS configuration option?

36degrees commented 1 year ago

Not that I can immediately think of, but I think changing that would be a breaking change as it'd require folks to update their markup.

36degrees commented 1 year ago

Another workaround is to manually set window.location.hash before the GOV.UK Frontend JS kicks in, which avoids the viewport scrolling to the tab:

<script>
window.location.hash = 'id-of-tab'
</script>