MENU
Translating with MutationObserver & Getting Query String Value
Some events cannot be hooked onto certain elements. For instance, you can't define a 'load' event handler for a <div> element. What you can do is to execute JavaScript after the element.
RESETRUNFULL
<div>…<div><script>
document.querySelector(“div").innerHTML = …;</script>
Contrasting events on existing elements, a MutationObersver allows you to invoke a function when a DOM tree is modified.
This implements a simple multi-lingual translator for a website.
RESETRUNFULL
RESETRUNFULL
// translations.jsvar languages = ['en','fr','de'];var translations = {"___000___":[
"Best Web Translator",
"Meilleur traducteur Web",
"Bester Webübersetzer"],"___001___":[
"Welcome to the Best Translator of the Web",
"Bienvenue chez le meilleur traducteur du Web",
"Willkommen beim besten Übersetzer im Web"],"___002___":[
"Do you have something to translate today?",
"Avez-vous quelque chose à traduire aujourd'hui?",
"Haben Sie heute etwas zu übersetzen?"],"___003___":[
"Seriously I can help you.",
"Sérieusement, je peux vous aider.",
"Im Ernst, ich kann dir helfen."],}
<!DOCTYPE html><html><head>
<meta charset="utf-8"/>
<script src="translations.js"></script>
<script>
var langInd = languages.indexOf((new
URLSearchParams(location.search)).get('lang'));
if (langInd==-1) langInd = 0;
function translateNode(n){
let t = n.textContent;
if (n.childNodes.length>0)
for (let nn of n.childNodes) translateNode(nn);
else if (t.includes("___")){
let ti = t.substring
(t.indexOf("___"),t.lastIndexOf("___")+3);
if (translations[ti]) n.textContent =
t.replace(ti,translations[ti][langInd]);
}
}
function translator(mutations){
for (let m of mutations){
for (let n of m.addedNodes) translateNode(n);
}
}
(new MutationObserver(translator)).
observe(document, {childList:true,
attributes:true, characterData:true, subtree:true});
</script>
<title>___000___</title></head><body>
<h1>___001___</h1>
<div>
<p>___002___</p>
<strong>___003___</strong>
</div></body></html>
(http://myhost.com/mutationobserver.html?lang=fr)
Note that if you invoke the observe() function at the end of the body, it will not observe the part of the body already loaded.