2

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.

user113716
  • 318,772
  • 63
  • 451
  • 440
Hubro
  • 56,214
  • 69
  • 228
  • 381

2 Answers2

3

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') });
RReverser
  • 1,940
  • 14
  • 15
  • This was my backup plan. I'll have to go through all my language files and add IDs, as well as go through my entire web application and add IDs to all my elements. I was hoping jQuery contained a magic solution, as it has so often before. – Hubro Jun 29 '11 at 17:04
  • @Codemonkey And how do you lang files look like now? – RReverser Jun 29 '11 at 17:33
  • json files with label names and label texts. The label names aren't fit as IDs though – Hubro Jun 29 '11 at 17:59
  • Then you may use, for example, "name" attribute to store this names and change jQuery selector to $('[name="' + elemName + '"]'). – RReverser Jun 30 '11 at 02:17
2

Are you open to using other types of technologies? If so, angularjs seems like exactly what you need.

Groovetrain
  • 3,315
  • 19
  • 23