Javascript

On this page, we describe all the functions exposed by the Weglot JS library

Getting started

Let's include Weglot's client code into your site and get started with translations.

  1. Go to your Weglot dashboard (https://dashboard.weglot.com/) , start a new project. Depending on the technology you chose, you will integrate Weglot using the Javascript library.

  2. Edit your HTML file, and right after the</head>tag, append the code that is shown to you. It should look like:

<script type="text/javascript" src="https://cdn.weglot.com/weglot.min.js"></script>
<script>
Weglot.initialize({
api_key: 'YOUR_API_KEY'
});
</script>

Make sure you replace YOUR_API_KEYwith the API key you got in the step one.

Initialization code

As you've seen in the "Getting started" section, Weglot gets initialized through this code:

Weglot.initialize(options)

Where options is a Javascript object with properties defined as follows. Only api_key, (in bold) are required. Weglot uses the api_key to retrieve link to your project and know what language to show on the language button. You can change options directly in your project settings : https://dashboard.weglot.com/projects/edit

You can also add in the option variable custom parameters that will change the default behavior of the library.

Property

Description

Default

Example

api_key

Your Weglot API Key

styleOpt

A javascript object describing the default styling of the Weglot language switcher button

{ fullname: true, withname: true, is_dropdown: true, classF: '' }

styleOpt["withname"]

true to display a label text next to each language options. false otherwise

true

styleOpt["fullname"]

If withname is true, true to display the full name of the language.false to just show the 2-letter language code

true

styleOpt["is_dropdown"]

true to display the language selector as a dropdown. false to show it as a list

true

styleOpt["classF"]

A String. The extra CSS class to apply to the button elements. Add wg-flags to show flags (by default they will be mat rectangles).

""

"wg-flags flag-3" "wg-flags"

waitTransition

true to prevent content blinking when translating a new page.

true

hideSwitcher

true to prevent Weglot from creating language switchers, false otherwise. Defaults to false. If you set it to true, it's your responsibility to use the Client-side API or link hooks to change languages on the page

false

translateSearch

true to translate search queries on the website, false otherwise.

false

translateImages

true to translate images' URLs on the website, false otherwise

true

searchsForms

A comma-separated list of CSS selectors of search form elements to watch for. Useful only if translateSearch is true. The form has to send a q parameter for it to work

""

cache

Setting this to true greatly improves user experience by caching Weglot's translations into your visitors' browser. Translations are kept up-to-date asynchronously.

false

switchers

A Javascript Array of Objects representing several language switchers on the page

[]

switchers[]["styleOpt"]

A Javascript Object defined exactly like styleOpt

switchers[]["target"]

The CSS selector of the node that the switcher will be a child of

".site-header__section--title"

switchers[]["sibling"]

The CSS selector of the next sibling element of the switcher. null for the last element inside the target

null

extraDefinitions

A Javascript Array of Objects representing extra translation definitions

[]

extraDefinitions[]["selector"]

A CSS selector to the element(s) you want to target

"input.someclass[type=text]"

extraDefinitions[]["attribute"]

The name of the attribute you'd like to translate

"data-tooltip"

extraDefinitions[]["type"]

Optional. The WordType of the text that you'd like to translate

1

2

A full example could look like this:

Weglot.initialize({
api_key: "wg_1234567897e2ea993d291b571c2ec93b0",
styleOpt : { fullname: true , withname: true , is_dropdown: true , classF: "wg-flags flag-3" },
translateSearch: false,
switchers: [
{
styleOpt:{
fullname: true,
withname: true,
is_dropdown: true,
classF: "wg-flags flag-3"
},
containerCss: "",
target: ".site-header__section--title",
sibling: null
}
]
});

Client-side API

The JS library exposes functions that you can use anywhere in your code. (just make sure the library is already loaded when calling one of these functions)

Weglot.getCurrentLang()

Parameters
Response

None

String: the ISO 639-1 2-letter code of the current language on the page

Weglot.getLanguageName(code)

Parameters
Response

String: the local name of the language, as defined by ISO 639-1

For example, calling Weglot.getLanguageName("es") returns "Español"

Weglot.getBestAvailableLanguage()

Parameters
Response

None

  • code(String): the ISO 639-1 2-letter code of the best available language

This function checks the visitors preferred languages, and finds the best match among the languages you support on Weglot. It's the function used internally when you use the autoSwitch function

Weglot.search(term, callback)

Parameters
Response
  • term(String): Any term written in the current language of the page.

  • callback(Function): A function that will be called whenever the search term in the original language is available. Takes one String argument

true if there is a search to be made (the current language of the page differs from the original language)

false if there is no search to be made. In this case the callback is called immediately with the original term

Weglot.switchTo(code)

Parameters
Response
  • code(String): the ISO 639-1 2-letter code of a language you're supporting on your website

    code is either originalLanguage or one of the destinationLanguages

Nothing

Weglot.on(eventName, callbackFunction)

You can subscribe your own code to Weglot-specific events. When these events occur, the callback function you have defined will be called.

languageChanged

This is called right after a language has changed on the page

Weglot.on("languageChanged", callbackFunction)

The callback function will be called with two optional arguments:

  1. newLanguage (String): the 2-letter code of the language the page changed to

  2. previousLanguage (String): the 2-letter code of the previous language of the page

Example:

Weglot.on("languageChanged", function(newLang, prevLang) {
console.log("The language on the page just changed to (code): " + newLang)
console.log("The full name of the language is: " + Weglot.getLanguageName(newLang))
})

initialized

This is called right after the call to Weglot.initialize(options) has been successful, but before the switchers are created and the page is translated

Weglot.on("initialized", callbackFunction)

The callback function will be called with no argument.

If you register your callback after Weglot has been initialized, this will have no effect.

To check whether Weglot is already initialized or not, you can read the boolean Weglot.initialized

switchersReady

This is called right after the switchers have been created.

Weglot.on("switchersReady", callbackFunction)

The callback function will be called with one optional argument: initialLanguage

Example:

Weglot.on("switchersReady", function(initialLanguage) {
console.log("the switchers are ready, I can tweak them")
})

Weglot.off(eventName, callbackFunction)

With Weglot.off, you can unsubscribe the events you subscribed to with Weglot.on

Parameters
Response

eventName(String): mandatory field, the name of the event you want to unsubscribe from

callbackFunction(Function): optional field, if you'd like to target a specific function

true if one or more events have been unregistered

false otherwise

Weglot.initialize(options)

Called to initialize Weglot. See Initialization code

Link hooks

By default, Weglot will show a language switcher on your page. Either on the bottom-right side or where it has been set through the switchers options. In some cases, you might want to not use Weglot's switcher at all and use menu entries from the CMS you're integrating in. You might also want to create your own switcher and not use Weglot's CSS.

When Weglot gets initialized, every link that matches one of these CSS selectors will be "hooked" to a Weglot.switchTo action automatically:

  • a[href='#Weglot-xx']

  • a[href$='change-language.weglot.com/xx']

... where xx is the ISO-639-1 code of the target language

When the links are "hooked", the original href attribute also gets removed, and the class weglot-link is added to them. The current language also has the class weglot-link--active

Example - Anchor

I want to use the native menu feature of my CMS. Let's say my original language is English, and I want to translate to French and Spanish.

My menu would have 3 entries, as follows:

Text

Link

English

#Weglot-en

Français

#Weglot-fr

Español

#Weglot-es

I have now a "native" language switcher that works for all these languages. If I need to apply specific styling to the current language, I can target the weglot-link--activeclass.

Sometimes, the CMS you will be using won't allow for anchor links in the menu (e.g. Wix). In this case, you can use fake links that will be replaced when Weglot initializes:

Text

Link

English

http://change-language.weglot.com/en

Français

http://change-language.weglot.com/fr

Example: create your own switcher

function() {
// CHANGE THIS SELECTOR to the element you want to add your custom switcher to.
var myDiv = document.getElementById("myDiv");
//Create array of options to be added
var availableLanguages = [Weglot.options.originalLanguage].concat(Weglot.options.destinationLanguages.split(','))
//Create and append select list
var selectList = document.createElement("select");
myDiv.appendChild(selectList);
var currentLang = Weglot.getCurrentLang();
//Create and append the options
for (var i = 0; i < availableLanguages.length; i++) {
var lang = availableLanguages[i];
var option = document.createElement("option");
option.value = lang;
option.text = Weglot.getLanguageName(lang);
if (lang === currentLang) {
option.selected = "selected";
}
selectList.appendChild(option);
}
selectList.onchange = function(){
Weglot.switchTo(this.value);
};
Weglot.on("languageChanged", function(lang) {
selectList.value = lang;
})
}()