Skip to content

Language change events

When a visitor picks a language in the SwiftLingo language switcher, it dispatches a swiftlingo:languageSet event on window, right before the browser navigates to the translated page.

Event swiftlingo:languageSet (a CustomEvent)
Dispatched on window
event.detail.language The chosen language code in lower case, for example fr or pt-br

Example: track the choice in your analytics

Section titled “Example: track the choice in your analytics”

The page is about to unload, so send data with something that survives navigation, such as navigator.sendBeacon:

window.addEventListener('swiftlingo:languageSet', (event) => {
const language = event.detail.language;
navigator.sendBeacon('/analytics/language', JSON.stringify({ language }));
});

The event fires on the page the visitor is leaving. To run code for the language of the current page, read the lang attribute instead; SwiftLingo sets it on translated pages:

const language = document.documentElement.lang; // e.g. "fr" on fr.example.com

On your original site, lang is whatever your own HTML sets.