Robert M.
Robert M.

Reputation: 1367

Are there any drawbacks when setting the HTML lang attribute dynamically on the client side?

We are currently serving the initial index page for a single page application without the lang attribute set on the HTML tag. At the moment we are also not setting it dynamically after the page is loaded.

Are there any problems with screen readers if the language is set dynamically instead of already setting it on the initial page?

Upvotes: 7

Views: 1604

Answers (4)

Jannchie
Jannchie

Reputation: 1008

There is one very serious flaw:

Browsers that have automatic translation (chrome, edge), cannot detect language changes. When using the translation feature, they will always try to translate from the language set at the beginning of the page.

Upvotes: 0

aardrian
aardrian

Reputation: 9009

No. The previous two answers have it, but I am linking a CodePen demo that I use for clients / talks just so you can test and confirm it for yourself:

http://codepen.io/aardrian/pen/eBOrZY

I toggle the main, but I have also done it on the html and you can tweak the following code in the pen to do so:

function toggleLang(l) {
  var m = document.querySelector('main');
  m.setAttribute('lang', l);
}

Upvotes: 0

Adam
Adam

Reputation: 18807

Modern screenreaders understand javascript and use the javascript modified DOM instead of the initial DOM.

As long as you do not change the lang attribute too late (after the screenreader already started to speak), it should work.

Note that switching language might result in some bugs if you do not also change the current URL using the HTML5 api history.

Upvotes: 4

Frank34
Frank34

Reputation: 79

No, not to my knowledge. We have done it already in a published product. Our case was getting the wished language for Spell-Check in contenteditables. So we dynamically change the lang attribute of all elements and it just works fine.

Upvotes: 0

Related Questions