Frontend API: Methods

Available methods for the on-site Localize script

This page describes the methods that are available in the Localize object after the Localize.initialize()method has been called.

  • Check out the Quickstart for Web guide for step-by-step instructions for adding our client-side JavaScript library to your site.

currency()

Convert a monetary value from one currency to another, using the current exchange rate.
Rates are updated hourly.

Localize.currency(originalValue, { originalCurrency: fromCurrency, targetCurrency: toCurrency }, callback);
  • originalValue Required (Number). The original monetary value that you want to convert.
  • fromCurrency Required (String). The default source currency code, to be converted from.
  • toCurrency Required (String). The new currency code, to be converted to.
  • callback Required. Receives err and value arguments.

📘

Currency Codes

The fromCurrency and toCurrency variables expect a 3-letter identifier using the
ISO 4217 Currency Codes.

Localize.currency(1234.56, { originalCurrency: "USD", targetCurrency: "CAD" }, function (err, value) {
  console.log('Converted value = ' + value + ' CAD');
});

// OUTPUT:
Converted value = 1573.62 CAD

detectLanguage()

Returns the visitor's list of preferred languages, based on the browser's accept-language header.

Localize.detectLanguage(callback);

The following are the available options for the detectLanguage() method.
NOTE: All option names are case-sensitive!!

  • callback
    Required. A string with the name of the callback function, or the function itself.
Localize.detectLanguage(function(err, languages){
  if (err) return console.log(err);
  console.log(languages)
});

/*
 * Sample output for a browser with English, Spanish and French:
 
 ["en-US", "es", "fr"]
 
 */

getAvailableLanguages()

Returns all available languages for the project.

Localize.getAvailableLanguages(callback);

The following are the available options for the getAvailableLanguages() method.
NOTE: All option names are case-sensitive!!

  • callback
    Required. A string with the name of the callback function, or the function itself.
Localize.getAvailableLanguages(function(err, languages) {
  if (err) return console.log(err);
  console.log(languages)
});

/* 
 * Sample output:
 
 [
   {code: "es", name: "Español"},
   {code: "de", name: "Deutsch"},
   {code: "pt-BR", name: "Português (Brasil)"},
   {code: "zh", name: "中文(简体)"},
   {code: "en", name: "English"}
 ]
 
 */

getExchangeRate()

Returns the exchange rate between the provided currencies.
Rates are updated hourly.

Localize.getExchangeRate(fromCurrency, toCurrency, callback);
  • fromCurrency Required. The default source currency code, to be converted from.
  • toCurrency Required. The new currency code, to be converted to.
  • callback Required. Receives err and rateData arguments.

📘

Currency Codes

The fromCurrency and toCurrency variables expect a 3-letter identifier using the
ISO 4217 Currency Codes.

The following is the JSON schema of the returned rateData.

rateData schema:
  {
     fromCurrency
     toCurrency
     rate
  }

The following is an example that converts $100 US dollars to Euros (value may be different than today's rates).

var dollarsUSD = 100;
var dollarsEUR = null;

Localize.getExchangeRate('USD', 'EUR', function(err, rateData) {
  console.log('Rate data: ', rateData);
  dollarsEUR = dollarsUSD * rateData.rate;
  console.log('Dollars Euro: ', dollarsEUR);
});

// OUTPUT:
Rate data: 
{
  fromCurrency: "USD"
  toCurrency: "EUR"
  rate: 0.896624
}
Dollars Euro: 89.66239999999999

getLanguage()

Returns the language code for the current language of the page. If a language hasn't been set, the language code of the source language is returned.

var currentLanguageCode = Localize.getLanguage();

getSourceLanguage()

Returns the language code for the source language of the current project.

var sourceLanguageCode = Localize.getSourceLanguage();


hideLanguagesInWidget()

Call this method to remove languages from the Localize default language-switching widget.

Sometimes, you may want to display a different set of languages in the widget on different pages of your website or for different customers using your SaaS tool or when you are working on the translations for a language. Call this method with the list of target language codes you'd like to hide in the widget. Note: the source language will always be included in the widget.

document.addEventListener("DOMContentLoaded", function() {
  Localize.hideLanguagesInWidget(['de', 'fr']);
});

hideWidget()

Calling this function will hide the default Localize language-switching widget if it's currently visible.
You can use this function to hide the widget on certain pages.

Localize.hideWidget();

🚧

Overrides Project Setting

Note: Using this function will override the "Display language widget in your website" setting in the Widget settings for the Project.


initialize()

See the Frontend API: Initialization page for instructions on installing the code snippet and setting various options in the initialization method.


on()

Attach an event handler to Localize events.

Localize.on(eventName, fn(data));
  • eventName Required. Name of event to bind to. Can optionally be namespaced: "setLanguage.ns"
  • fn Required. Event handler - receives the event data

Available events:

'error'

This event is generated when there is an error when initializing the library.

  • The error string will describe the error that occurred.
Localize.on('error', function(error) {
   console.log("Oh No! You just got this error: " + error)
});

/*
 * OUTPUT: 
 * Oh No! You just got this error: Invalid Project Key
 */

'initialize'

This event is generated when Localize is initialized.

  • The data object contains the values of any options that were sent in when initializing.
    • key - the Project Key
    • any other options that were set...

NOTE: Be sure to put this call before your initialize() call so that it is ready to listen for the initialize event.

Localize.on("initialize", function(data) {
  console.log("initialize: ");
  console.log(data);
});

Localize.initialize({
  key: '[[app:key]]', 
  rememberLanguage: true,
  // other options go here, separated by commas
});

/*
 * OUTPUT:
initialize:
{…}
key: "[[app:key]]"
rememberLanguage: true
 */

'setLanguage'

This event is generated when the language is switched.

  • The data object contains:
  • from - the old language code
  • to - the new language code
Localize.on("setLanguage", function(data) {
  console.log("setLanguage: from '" + data.from + "' to '" + data.to + "'");
});

/*
 * OUTPUT: 
setLanguage: from 'en' to 'es'
 */

'updatedDictionary'

This event is generated when any changes are made to any phrases in the library in the source or target language.

  • The data object contains:
    • version - the latest version # of the dictionary
    • language - the current target language code
    • dictionary: contains an array of phrase objects in the form:
      • "#source phrase": "target phrase"
Localize.on("updatedDictionary", function(data) {
  console.log("version = " + data.version);
  console.log("language = " + data.language);
  console.log("dictionary = ");
  console.log(data.dictionary);
});

/*
 * OUTPUT: 
version = 790
language = es
dictionary =
{…}
"#Back to Products": "Volver a Productos"
"#About": "Acerca de"
"#Add To Cart": "Añadir a la cesta"
"#Back to Top": "Volver arriba"
...
 */

'widgetLoaded'

This event is generated when the default Localize language switching widget element has fully loaded in the DOM. You can use this event to trigger other events in your code, knowing that the widget is loaded.

Localize.on("widgetLoaded", function() {
  console.log("widgetLoaded = true");
});

/*
 * OUTPUT: 
 * widgetLoaded = true
 */

off()

Remove an event handler.

Localize.off(eventName[, fn]);
  • eventName Required. Name of event to unbind from. Can optionally be namespaced: "setLanguage.ns"
  • fn Optional. The function to unbind from the event.

number()

Convert the format of a number to the format used in the currently selected language/locale.

Localize.number(originalValue, callback);
  • originalValue Required (Number). The original numerical value that you want to convert.
  • callback Required. Receives err and value arguments.
Localize.number(123456.789, function(err, value) {
     console.log('convertedNumber = ' + value);
});

// Output with Spanish set as the current language:
convertedNumber = 123.456,789

phrase()

Saves the phrase, if unrecognized, to your Localize project. Useful for ensuring rarely printed text (ie. an obscure error message) is translated. Returns the phrase it was passed.

Localize.phrase(phrase);
  • phrase Required. A string or an array of strings

prefetch()

Speed up language switching by prefetching translations by language.

Localize.prefetch(languages);
  • languages Required. Accepts a string or an array of language codes (ex. 'zh-CN')

setLanguage()

Translates the page into the given language.

Localize.setLanguage(languageCode);

The following are the available options for the setLanguage() method.
NOTE: All option names are case-sensitive!!

  • languageCode
    Required. Language codes can be found on your Languages page.

setWidgetLanguages()

Call this method to set the languages you'd like to have active in the Localize default language-switching widget.

Sometimes, you may want to display a different set of languages in the widget on different pages of your website or for different customers using your SaaS tool. Call this method with the list of target language codes that you'd like to make available in the widget. Note: the source language will always be included in the widget.

document.addEventListener("DOMContentLoaded", function() {
  Localize.setWidgetLanguages(['es', 'fr']);
});

showWidget()

Calling this function will show the default Localize language-switching widget if it's currently hidden.

Localize.showWidget();

🚧

Overrides Project Setting

Note: Using this function will override the "Display language widget in your website" setting in the Widget settings for the Project.


translate()

Retrieves the translation for an existing source phrase in the currently active language, or adds a new source phrase using the contents in the input parameter. input can be plain text or text within HTML, and can optionally contain variable data.

Localize.translate(input, variables, callback);
Localize.translate(input, callback);  // optionally without variables
Localize.translate(input);  // optionally without variables nor callback

The following are the available parameters for the translate() method.
NOTE: All parameter names are case-sensitive!!

  • input

Required. Can be text, HTML, or native DOM elements

This is a phrase in the source language. This method only translates content from the source language into any of your target languages.

  • variables

Optional. An object with key:value pairs of variables that will be replaced in the input parameter.

  • callback

Optional. The callback function will trigger once translations have been fetched from Localize.

  • returns

a string

If the Localize.translate() input parameter is a string, instances of %{variable} will be replaced with the given value in the variables object.

📘

Matching Variable Names

Note that the variable name in the input parameter must match the variable name in the variables parameter, or it will not function correctly.

You may also use HTML <var> tags in the string. For example, all of the following variations are supported:

Localize.translate('My name is %{name}', { name: 'Joe' }, callback);
Localize.translate('My name is <var name></var>', { name: 'Joe' }, callback);
Localize.translate('My name is <var name>Joe</var>', callback);

📘

Retrieving translations via a CSS class name

If you are looking to retrieve the translation of a DOM node via a CSS class name, you'll have to provide an index to the array that will be returned since there can be more than 1 instance of a node with that CSS class on the page. Localize cannot return the entire array of nodes that match the CSS class.

Localize.translate(document.getElementsByClassName('foo')[1]);
or
Localize.translate($('foo')[1]);

Localize.translate() returns:

  • If the active language is the source language of the page, Localize.translate will return the untranslated phrase, adding the phrase to your dashboard if it didn't previously exist.
  • If the active language is a target language and the phrase exists and has been translated, Localize.translate will return the translated phrase.
  • If the phrase is a new phrase, Localize.translate will return the untranslated phrase and add it to your dashboard.

Localize.translate can be used with or without a callback. We highly recommend using the callback approach if you're calling Localize.translate in the first 10 seconds of page load to ensure that the latest translations are available. The callback will allow the translation to be delayed until translations have been fully loaded into the browser. If the translations are already loaded, the callback is executed immediately.

📘

Case Insensitivity

Since all HTML attributes are case insensitive, when defining a <var> name, be advised that the resulting attribute in the returned HTML translation will be converted to all lowercase, for consistency.

For example:
Localize.translate('My name is %{name}', { name: 'Joe' }, callback);

Localize.translate('My name is %{name}', { name: 'Joe' }, function(translation) {
  console.log(translation);
});

📘

Reserved Variable Names

Note that you cannot use any HTML attribute names as variable names, including (but not limited to):
accept, accept-charset, accesskey, action, align, alt, async, autocomplete, autofocus, bgcolor, border, checked, cite, class, color, cols, colspan, disabled, download, href, hreflang, multiple, placeholder, readonly, pluralize, draggable, dropzone, hidden, id, spellcheck, required, reversed, rows, selected, src, style, tabindex, ignore, language


translateImmediate()

Provides an immediate translation of the given phrase.

One possible use case for using this method is to support searching in a target language.

Localize.translateImmediate(targetLanguage, phrase, callback)

The following are the parameters for the translateImmediate() method.
NOTE: All parameter names are case-sensitive!!

  • targetLanguage

Required. This is the language code for the language into which you want to translate the given phrase.

The source language is assumed to be the currently selected language on the website.

  • phrase

Required. The phrase that you'd like to translate.

  • callback

Required. A callback function that accepts an error and a result parameter.

The following details what the method does to retrieve or create the translation.

  • If you are translating from a target language to the source language of your project:
    • ...it first looks to see if the phrase already exists in your project and if it does it returns the existing source language phrase.
    • ...it then looks at the Glossary and if the phrase matches a glossary term it returns the source language version of the matching term.
    • ...otherwise, it generates a machine translation for the phrase and returns it.
      • The given phrase is not added to your dashboard, it is a one-time use translation.
  • If you are translating between target languages it will generate a machine translation for the phrase and return it.
    • The given phrase is not added to your dashboard, it is a one-time use translation.

Using these details you may be able to better "train" the method to use preexisting content in your dashboard.

Localize.translateImmediate('en', 'mejores sofás blancos', function(err, result) { 
  console.log('err: ', err, 'result: ', result);
});

/* Output:
err: null
result: 
  phrase: "mejores sofás blancos"
  targetLanguage: "en"
  translation: "best white sofas"
*/ 

📘

Subscription-Specific

This feature is not available on all subscription plans. Please contact your Account Executive or Customer Success Manager for details.


translatePage()

Returns the DOM node (or nodes) within the <body> tag that was (were) translated, based on your initialization settings, using the currently selected language. For example:

  • If you are using the standard initialization settings, it will return the entire <body> node, translated to the currently selected language.
  • If you have translateBody set to false, it will only return nodes that have the CSS class or id of localizejs.

Note: This pulls the translations from the published phrases in your project and replaces the source content with those translations. It does not automatically translate new phrases. (Use the translateImmediate() method for that.) If new phrases are found on the page they will be added to your Localize dashboard as new phrases.

Localize.translatePage();

untranslate()

Untranslates a specified element on the page.

Use Localize.untranslatePage() if untranslating the whole page.

Localize.untranslate(element);
  • element Required. A DOM node to untranslate

untranslatePage()

Untranslates all text on the page and switches the language back to the source language.

Localize.untranslatePage();