dynamically change javascript source with onclick event

102 views Asked by At

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.

1

There are 1 answers

4
Alex On

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.