Skip to content

Instantly share code, notes, and snippets.

@fupslot
Last active December 16, 2015 13:48
Show Gist options
  • Save fupslot/5444288 to your computer and use it in GitHub Desktop.
Save fupslot/5444288 to your computer and use it in GitHub Desktop.
<input type="text" class="i18n" data-labels="value#str001 placeholder#str002" />
<button class="i18n" data-labels="innerText#str003">Click Me</button>
<div class="i18n" data-labels="innerText#str004">This string will never be translated</div>
<script>
function i18n_parse (rootElement, labelAttribute, iterator) {
if (arguments.length === 1 && typeof arguments[0] === "function") {
iterator = arguments[0];
rootElement = null;
labelAttribute = null;
}
if (arguments.length === 2 && (
typeof arguments[0] === "object" &&
typeof arguments[1] === "function")) {
rootElement = arguments[0];
iterator = arguments[1];
labelAttribute = null;
}
if (iterator === undefined) { throw "An iterator must be specified"; }
if (typeof labelAttribute !== "string") {
labelAttribute = "data-labels";
}
if (window.jQuery && rootElement instanceof jQuery) {
rootElement = rootElement.get(0);
}
if (rootElement == undefined) {
rootElement = document;
}
var nodes = rootElement.querySelectorAll(".i18n");
Array.prototype.forEach.call(nodes, function (node) {
if ( node.hasAttribute(labelAttribute) ) {
var a = node.getAttribute(labelAttribute);
if (a.trim) { a = a.trim(); }
var localStrings = a.split(" ");
localStrings.forEach(function (localString) {
var b = localString.split("#")
, attrName = b[0]
, stringName = b[1]
, stringValue = iterator(stringName);
if (typeof stringValue !== "string") { stringValue = ""; }
if (stringValue.trim) { stringName = stringName.trim(); }
if ( stringValue && attrName.toLowerCase() == "innertext") {
node.innerText = stringValue;
}
else if ( stringValue ) {
node.setAttribute(attrName, stringValue);
}
});
}
});
}
// USAGE
var strings = {
"str001": "John Doe",
"str002": "Type your name...",
"str003": "Click for Love",
"str004": ""
};
i18n_parse(document, function (stringName) {
return strings[stringName];
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment