// An extremely basic translation library // // Example usage: // // Set some html to be translated. Do this using the 'data-translate' attribute: // //
Test
//
keep em tag
// // // Obtain all the phrases to be translated via js debug console: // // Translate.phrasesAsJson(); // // Use that template to translate the phrases into another language. // Leave the key the same. Change the value to the new language. // // Create a js file to load the new phrases. In this example for Spanish, // es.js will contain the following code: // // Translate.loadForeignPhrases("es", { // "Test": "Test in Spanish", // "keep em tag": "keep em tag in Spanish", // "Example text": "Example text in Spanish" // }); // // In your UI put a listener for clicking on the Spanish button: // // mySpanishButton.addEventListener("click", function() { // Translate.setLanguage("es"); // }); // myEnglishButton.addEventListener("click", function() { // Translate.setLanguage("en"); // }); Translate = new (function() { var defaultLanguage = "en"; var allPhrases = {}; allPhrases[defaultLanguage] = {}; // Node types var text = { selector: "[data-translate]", getKey: function() { return this.textContent.trim().replace(/\s+/g, " "); }, setPhrase: function(p) { this.textContent = p; }, } var html = { selector: "[data-translate-html]", getKey: function() { return this.innerHTML.trim().replace(/\s+/g, " "); }, setPhrase: function(p) { this.innerHTML = p; }, } var placeholder = { selector: "[data-translate-placeholder]", getKey: function() { return this.getAttribute("placeholder").trim().replace(/\s+/g, " "); }, setPhrase: function(p) { this.setAttribute("placeholder", p); }, } // Get elements to be translated var allEls = getEls(text) .concat(getEls(html)) .concat(getEls(placeholder)); // Provides access to phrases from a non-default language. // See phrases_en.js for example usage. this.loadForeignPhrases = function(language, phrases) { allPhrases[language] = phrases; } // Displays a different language, eg "en" or "fr" this.setLanguage = function(language) { for (var i=0; i