Search code examples
javascripthtmllocalizationdom-events

When is html languagechange event fired in the browser?


I am trying to add localization in a simple web app. There is a languagechange event as per Mozilla docs.

My questions is:

  • when is this event actually fired?

Here is what I tried.

  • page html tag has lang attribute <html lang='ar-SA'>
  • user can use some dropdown to switch to another language.
  • the dropdown, changes the lang attribute on html tag to the desired lang

I was hoping that changing lang attribute on root html tag will fire the languagechange event, which in turn I can use to load the content in new lang, but it does not.

Did I miss something obvious here?


Solution

  • The languagechange event is fired at the global scope object when the user's preferred language changes.

    window.onlanguagechange = function(event) {
      console.log('languagechange event detected!');
    };
    

    Check your Browser compatibility