Javascript

Don't hesitate to contact the team on Slack or at contact@weglot.com if you have any question.

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/) and get your API key in the "Project settings" menu (e.g. wg_1234567897e2ea993d291b571c2ec93b0)

  2. Edit your HTML file, and right after the<body>tag, append the following code:

<script type="text/javascript" src="https://cdn.weglot.com/weglot.min.js"></script>
<script>
Weglot.setup({
api_key: 'YOUR_API_KEY',
originalLanguage: 'en',
destinationLanguages : 'fr,es',
});
</script>

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

You can now refresh your page. French and Spanish are now translation options for your website in English!

The full list of language codes we support is available at https://weglot.com/documentation/available-languages

Initialization code

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

Weglot.setup(options)

Where options is a Javascript object with properties defined as follows. Only api_key, originalLanguage and destinationLanguages (in bold) are required.

Property

Description

Default

Example

api_key

Your Weglot API Key

originalLanguage

The ISO 639-1 code of the original language of your website

"en"

destinationLanguages

A comma-separated list of 2-letter codes of languages you wish to be able to translate your website to.

"fr,es"

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"

autoSwitch

true to automatically switch to the user's preferred language if available. false otherwise.

false

autoSwitchFallback

If none of your visitor's languages match the available languages, Weglot will fallback to the original language. Set this option to select another fallback language

""

"en"

exceptions

A comma-separated list of CSS selectors of elements to exempt from translation

""

"#not-this-id,.not-this-class"

dynamic

A comma-separated list of CSS selectors of elements to watch for changes. If content changes dynamically inside one of the targeted elements, Weglot will translate it.

""

".content-will-change-here"

excludePaths

A comma-separated list of paths to exclude from translations. The current path will be tested against Regex strings.

""

"/blog/,/checkout/\d+"

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.setup({
api_key: "wg_1234567897e2ea993d291b571c2ec93b0",
originalLanguage: "en",
destinationLanguages : "es,fr",
styleOpt : { fullname: true , withname: true , is_dropdown: true , classF: "wg-flags flag-3" },
exceptions: "#not-this-element,.not-this-class.p",
excludePaths: "",
dynamic: ".a-container-of-dynamic-content",
autoSwitch: true,
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

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.setup(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.setup(options)

Called to initialize Weglot. See Initialization code

JS Library versions

Weglot's JS library comes in different versions. They are all stored in our CDN in a minified file.

Depending on the version you would like to use, you may want to change first line of code in the "Getting started" section. For example, to use the standard version of Weglot JS (which is available at https://cdn.weglot.com/weglot.min.js), the first line will be:

<script type="text/javascript" src="https://cdn.weglot.com/weglot.min.js"></script>

Standard

Available at https://cdn.weglot.com/weglot.min.js

Use this version when you're not installing Weglot on one of our supported platforms (Shopify, Wix, Bigcommerce, etc.)

The standard library works well with CMS such as Squarespace, Webflow, or any other website.

Shopify

Available at https://cdn.weglot.com/weglot_shopify.min.js

This is the version used by Weglot's Shopify app. It's included automatically for you, hence we advise you to use our app directly for any Shopify store as some features come only from the app (Checkout translation, drag-and-drop placement, etc.)

This version adds a few Shopify-specific options and features.

Bigcommerce

Available at https://cdn.weglot.com/weglot_bigcommerce.min.js

This is the version used by the Bigcommerce app. It adds some convenience options that help setting the right customer language along the way, as well as support for cart drawers.

Wix

Available at https://cdn.weglot.com/weglot_wix.min.js

This is the version any Wix user should use, as it loads the Weglot app once the Wix website has been initialised properly.

Jimdo

Available at https://cdn.weglot.com/weglot_jimdo.min.js

This is the version any Jimdo user should use.

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;
})
}()