Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / HTML

onlanguagechange — handling preferred-language changes

The onlanguagechange attribute on body sets the Window object's handler for languagechange. The event signals a change in the user's preferred languages as understood by the browser, rather than a change to the document's lang attribute.

Version: WHATWG HTML Living Standard; index snapshot date recorded separately

Syntax

<body onlanguagechange="JavaScript statements">

onlanguagechange is an event handler content attribute used on body. Its value contains JavaScript executed for the Window object's languagechange event; this is not an ordinary event targeted at body.

The browser fires this event when its understanding of the user's preferred languages changes. Inside the handler, read navigator.languages for the ordered preferences or navigator.language for the most preferred language. Changing the lang attribute does not mean these preferences have changed, and the event itself does not translate the page.

In JavaScript, the same handler can be set through window.onlanguagechange. A new assignment replaces the previous handler in that slot; window.addEventListener('languagechange', handler) instead allows independent listeners to be registered. A page's security policy may block code in event handler attributes.

The example deliberately dispatches a synthetic event at window so its result does not depend on the device's language settings. It checks handler invocation, but neither changes preferences nor tests the browser's detection of a real preference change.

Examples

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>onlanguagechange demo</title>
</head>
<body onlanguagechange="document.getElementById('status').textContent = 'languagechange received'">
  <p id="status">Waiting</p>
  <button type="button" id="test">Test</button>
  <script>
    document.getElementById('test').addEventListener('click', () => {
      window.dispatchEvent(new Event('languagechange'));
    });
  </script>
</body>
</html>

Result

languagechange received

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources