javascriptjqueryweb-applicationslocalizationstring-table

Can I bind my HTML elements' text to an object of strings?


I'm making a web application using jQuery. All the elements of the web applications are created using jQuery (var $header = $("<div>");). I already have an object called stringtables where I have sub-objects called "no", "en" etc.

On page load the default is loaded and strings from it used for the text in all my elements. Is there any way I can tie all the elements to the string table, so when I switch string tables all the text on the website will change with it?

I want the application language to be changed without the page reloading.


Solution

  • No, you can't. You should manually create & call update function that will change contents of elements to new ones.

    For example:

    // function to set new strings to elements' contents
    function setLang(langStrings) {
      $.each(langStrings, function(elemId, elemText) { $('#'+elemId).text(elemText) });
    }
    // function to load language by name
    function loadLang(langName) {
      $.getJSON('/lang/' + langName + '.json', setLang);
    }
    // loading default language
    $(function() { loadLang('default') });