0

I’m a beginner in JavaScript and have the following problem, I have multiple pages in 2 languages. Later maybe more. I use a javascript var to set the language. Either:

Var language=”de”; or var language=”en”;

then I used this to load the correct language file:

<script src="javascript"+language+".js" type="text/javascript"></script>

Is there a way to change this variable with an onclick() event. So that it changes and stays changed until I change it again?

Thanks for you time.

Alex
  • 8,353
  • 9
  • 45
  • 56
  • 2
    Surely that doesn't work at the moment? – Alex Jun 25 '15 at 10:38
  • It works if I manualy change the variable. but i want an onclick event to change it and load the other .js file witch contains all the text. either in german or englisch. – Ronny Habets Jun 25 '15 at 10:42
  • So you have two identical JavaScript files which only differ in language? Let's say you have 10 languages and you find a bug somewhere, so you have to modify 10 JS scripts. – Liglo App Jun 25 '15 at 10:45
  • yes :) for now i only have to. It's goint to be a web app. and I dont want diffrent apps for diffrent langages. – Ronny Habets Jun 25 '15 at 10:49

1 Answers1

0

You can add scripts dynamically like this:

var selectorEls = document.querySelectorAll(".language-select");
var current;

function _handleClick ( ev ) {
  
  if ( current ) current.parentNode.removeChild(current)

  var language = ev.target.getAttribute("data-language");
  var newScript = document.createElement("script");
  var newSrc = "javascript" + language + ".js";
  newScript.setAttribute("src",newSrc);
  current = newScript;
  document.head.appendChild(newScript);
}

for ( var i = 0; i < selectorEls.length; i += 1 ) {
  
  selectorEls[i].addEventListener("click", _handleClick);
}
<a class="language-select" data-language="en">EN</a>
<a class="language-select" data-language="fr">FR</a>
<a class="language-select" data-language="de">DE</a>

This code binds clicks on a number of <a> elements, each with a language data attribute. Clicking on one creates a new <script> with the correct language and adds it to the page. It also deletes any scripts that you've added previously this way, to ensure no clashes.

Alex
  • 8,353
  • 9
  • 45
  • 56