Language link Hooks
Using Weglot links hooks to create your own language switcher
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 two 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, some 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

1
function() {
2
// CHANGE THIS SELECTOR to the element you want to add your custom switcher to.
3
var myDiv = document.getElementById("myDiv");
4
5
if (!Weglot) {
6
return;
7
}
8
9
//Create array of options to be added
10
var availableLanguages = Weglot.options.languages
11
.map(function(language) {
12
return language.language_to;
13
})
14
.concat(Weglot.options.language_from);
15
16
//Create and append select list
17
var selectList = document.createElement("select");
18
myDiv.appendChild(selectList);
19
20
var currentLang = Weglot.getCurrentLang();
21
22
//Create and append the options
23
for (var i = 0; i < availableLanguages.length; i++) {
24
var lang = availableLanguages[i];
25
var option = document.createElement("option");
26
option.value = lang;
27
option.text = Weglot.getLanguageName(lang);
28
if (lang === currentLang) {
29
option.selected = "selected";
30
}
31
selectList.appendChild(option);
32
}
33
34
selectList.onchange = function(){
35
Weglot.switchTo(this.value);
36
};
37
38
Weglot.on("languageChanged", function(lang) {
39
selectList.value = lang;
40
});
41
}()
Copied!
Last modified 1yr ago