Categories
programming

Useful Language-Changing JavaScript

Recently I had to quickly make a copy of the same web site iin a different language. Instead of coming up with complicated solutions (the web site isn’t that big and the second language was long overdue) I decided to copy the contents into a subdirectory and just substitute the contents in English with the same in Spanish.

The thought behind was that I can alternate between each page using simple javascript routine. So there I have example.com in English, example.com/sp/ same thing in Spanish. Same pages are named the same, so it’s example.com/about_us.html and example.com/sp/about_us.html – otherwise the script it useless.

The function is fairly simple:

function langChange() {
var pt = location.pathname;
var hs = location.host;

if (pt.length < 4) {
newloc = ‘http://’ + hs + ‘/sp/’;
} else {
if (pt.substring(0, 4) == ‘/sp/’) {
newloc = ‘http://’ + hs + ‘/’ + pt.substring(4);
} else {
newloc = ‘http://’ + hs + ‘/sp’ + pt;
}
}
window.location.assign(newloc);
}

Pretty universal, works everywhere. Set in as an onclick() event for your language changing butn and you’re good to go.

P.S. If you have much faith in Javascript – feel free to add ajax call to database for current page to figure out the counterpart in a different language.