dynamically change javascript source with onclick event -
i’m beginner in javascript , have following problem, have multiple pages in 2 languages. later maybe more. use javascript var set language. either:
var language=”de”; or var language=”en”;
then used load correct language file:
<script src="javascript"+language+".js" type="text/javascript"></script>
is there way change variable onclick() event. changes , stays changed until change again?
thanks time.
you can add scripts dynamically 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); } ( var = 0; < selectorels.length; += 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 number of <a>
elements, each language data attribute. clicking on 1 creates new <script>
correct language , adds page. deletes scripts you've added way, ensure no clashes.
Comments
Post a Comment