Search code examples
javascriptjsonmultilingual

How to preserve a language using javascript json


I use the following code in main.js and index.html for changing the language. It works to change the content of all three languages after pressing the buttons. However, the language will be returned to "ENG" every time the user changes the page. Is there a way to preserve the language the user selected at the very last time? Thank you.

main.js

/* Lang.json newly added */
$.getJSON("Lang.json", function(json) {
    console.log(json); // this will show the info it in firebug console
});

$(document).ready(function() {
// The default language is English
  var lang = "ENG";
  $(".lang").each(function(index, element) {
    $(this).text(arrLang[lang][$(this).attr("key")]);
  });
});

// get/set the selected language
$(".translate").click(function() {
  var lang = $(this).attr("id");
  $(".lang").each(function(index, element) {
    $(this).text(arrLang[lang][$(this).attr("key")]);
  });
});

index.html

<button class="translate" id="ENG">
    <a style="cursor: pointer;"><img src="assets/img/eng.png" /></a> 
</button>
<button class="translate" id="CHT">
    <a style="cursor: pointer;"><img src="assets/img/cht.png" /></a>
</button>
<button class="translate" id="CHS">
    <a style="cursor: pointer;"><img src="assets/img/chs.png" /></a>
</button>

Solution

  • You can use the localStorage to preserve the values. Check the below I have added comments.

    $(document).ready(function() {
    // The default language is English
      // Get the lang value from localStorage, if not set use the default value 'ENG'
      var lang = window.localStorage.getItem('lang') || "ENG";
      $(".lang").each(function(index, element) {
        $(this).text(arrLang[lang][$(this).attr("key")]);
      });
    
       // get/set the selected language
      $(".translate").click(function() {
        var lang = $(this).attr("id");
        // Save the lang value to localStorage to preserve
        window.localStorage.setItem('lang', lang);
        $(".lang").each(function(index, element) {
          $(this).text(arrLang[lang][$(this).attr("key")]);
        });
      });
    });