coderifous / jquery-localize Goto Github PK
View Code? Open in Web Editor NEWa jQuery plugin that makes it easy to internationalize your web site.
a jQuery plugin that makes it easy to internationalize your web site.
Intro: The script uses the getJSON utility function. This fn does not allow you to pass the aync param. The current script does a synchronous fetch using the getJSON function by setting then restoring the global ajaxSettings using the ajaxSetup function.
Problem: If the timeout is undefined prior to the localize call, then, when the previous value is stored away, it is stored as undefined. When you attempt to restore the timeout, since its original value is undefined, it does not reset the timeout back to undefined from the 500ms value that is set by the script - the ajaxSetup function simply calls jQuery.extend which ignores undefined vals. The result is that after executing the localize function, all ajax requests longer than 500ms timeout.
It is not working on aspx page but work on html page.
I guess this is more a feature request, but I'll post it here anyway :). I need to localize a web page, but it does not only contain html elements that need translation, there are also some dynamic div's, alerts and prompts. From what I have read it is not possible to do something like loading the localization normally (which localizes all elements on the page) and then after they are loaded use e.g. alert($.localize.load("msg_are_you_sure")) , which will use the last loaded localization. I figured I could use hidden inputs to store all these messages, but the approach I suggested might be more comfortable.
I'm sorry if I overlooked an existing feature here...
Example:
script
$('#commentCount').html(span data-localize="comment">comment);
script
span id='commentCount'></span
Is this possible ?
Thanks,
Glenn Lee
Hi,
I've translated my site in English, however, I made a dropdown where people can select a language.
The original language is Dutch in this case.
How can I revert back to Dutch without reloading the page?
Is the only option to create another translation in Dutch in a JSON file?
Thanks in advance!
Hello,
Some code is loaded in DOM by js (AJAX like), there is a way to get specific string right in the javascript ?
Thanks
Can I do It In head
for example head
meta
tag
or even
img title
... tag attrs
Hi,
I have a solution that works fine for Chrome/IE/Safari, but when run in Firefox it never loads the translated labels. Additionally the references JSON file takes 13 seconds to load (versus 5ms for Chrome).
How do I debug or attempt to resolve this ? Do the JSON files have to be saved in a certain way ?
Kind regards
Rich
Refers to old builder
script, which has been replaced. Probably want to replace with ref to CONTRIBUTING.md.
Hello,
How do I make the text to align right to left if the local browser language is Arabic or Hebrew ?
Just for these two languages, I want to html page to use direction:"rtl";
Thanks
Dan
Please pardon my ignorance but am having trouble creating a simple page with 5 sets of different languages that changes through the click of a button. I can't find relevant examples in your source.
Thank you.
It seems that the placeholder attribute is not supported for textarea 'elements'. Changing one line in the localizElement function fixes the 'issue', since you can use .val(value) on a textarea too:
localizeElement = function(elem, key, value) {
if (elem.is('input') || elem.is('textarea')) {
}
...
}
As a developer I would appreciate if the plugin could use parameters so that I don't have to localize any strings with eg. numbers or other constant strings.
In most cases it can be solved by separately localized "span" tags, but in particular cases such as "option" tags you can't. In this case localizing separately each string just because it differs only in the number is waste of space and developers time (not to mention it isn't very elegant).
Example:
Localized JSON
{
my_option: "My option {0}.{1}"
}
HTML:
...
Thanks for plugin, it works great for Chrome but we are having some issues for Safari. We are getting this error:
TypeError:
Any thoughts?
Hello - thanks for the plugin!
Is there a way to use this plugin to localize placeholder text?
For example, I'd like to localize "Please explain" in the following code:
<textarea id="explanation" placeholder="Please explain"></textarea>
Hi,
Instead of deciding which attribute to localize depending on the type of element (i.e. alt and src attributes for image), why don't you add the possibility to assign localized text to any attribute value?
For example:
Problem: localize div title attribute
Possible solution:
The code change for the plugin is easy (in the callback):
var elem, key, value, attr;
elem = $(this);
key = elem.attr("rel").match(/localize[(.?)]/)[1];
attr = elem.attr("rel").match(/attr[(.?)]/);
value = valueForKey(key, data);
if (attr != null) {
return elem.attr(attr[1], value);
}
else if ...
What do you think?
Yohan
I have one single json file containing all language data. but every time i replace the template inside div content i need to call the same command again which again loads the language json file from server. is it possible to just execute the replace command?
Hello,
thanks for great plugin.
Plugin have some issues if is using with JQM.
For example:
This:
Reset
should to display button, but with using with rel attr is button deformed.
I tried use other attr's than rel, fxp: i18n but still same result.
I think, that problem should be via Ajax loading of pages in JQM.
I will glad if any fix.
Greeting
Jiri
Hello and thank you for such a wonderful plugin.
I tried to integrate your library with my website yesterday and found out that not everything works as it should be...
The code from your documentation:
$("rel*=localize")
.localize("header")
.localize("sidebar")
.localize("footer")
does not work. It throws an exception "the object does not have localize method" when tries to apply localization from the second language pack. I'm using Chrome browser with jQuery 1.5.2.
It would be wonderful if you could fix this issue, thanks!
I'm using your great plugin on a site that also requires some images to be display in the local language, along with the alternative text.
My quick and dirty implementation based on the existing code is below.
if (elem.is('img')) {
value = valueForKey(key+'.alt', data);
if (value) {
elem.attr("alt", value);
}
value = valueForKey(key+'.src', data);
if (value) {
elem.attr("src", value);
}
}
Hello!
First of all, excellent plugin. I'm in a situation with a site where this could be quite useful. However, one problem I ran into was the inability to load cross-domain json files. I tweaked the build file a little bit to accommodate this scenario. I forked the repo before realizing that this was in coffeescript, which I am not familiar with, so I figure I will just post this js code here if you'd like to use it. If I can find some time next week, I'll be happy to take a look at coffeescript and do a proper pull request...
...
$.localize = function(pkg, options) {
var defaultCallback, intermediateLangData, jsonCall, lang, loadLanguage, notifyDelegateLanguageLoaded, regexify, valueForKey, wrappedSet;
if (options == null) {
options = {};
}
options.sameDomain = (typeof options.sameDomain == "undefined") ? true : options.sameDomain;
...
jsonCall = function (file, pkg, lang, level) {
...
ajaxOptions = {
url: file,
dataType: (options.sameDomain) ? "json" : "jsonp",
async: (options.sameDomain) ? false : true,
timeout: options.timeout != null ? options.timeout : 500,
success: successFunc,
jsonpCallback: (options.sameDomain) ? '' : 'successFunc'
};
...
Pretty simple change. Now by adding the option sameDomain: false (default is true) the script will use jsonp instead. I went ahead and specified the callback as the successFunc, since that's what it will wind up passing through anyway. Then all that's left would be formatting your external json file like so:
successFunc({ someString: "some text" });
Anyway, i'm sure others might find this useful. Great plugin and thanks for your work!
Hello,
This library is great and very useful. Many thanks.
I have a little problem using it on such elements, though:
when I chain on several JSON files.
If the entry does not appear in the last JSON file, then the value of the element is set to "", instead of keeping previous value, that would be the expected behaviour (that happened for all other elements, especially for labels).
This generates a problem of compatibility between jquery-localize and jquery-validate, where the use of input elements of such types is proposed.
This problem may be due to my incomplete understanding of the proper way to use this library. If it is the case, please tell me.
Anyway, I have an idea how to find a workaround, by treating localisation for such elements separately.
Many thanks for your patience.
I have this code:
var opts1 = {language: languageValue, pathPrefix: "/webapp/views/utility/resources/langs"};
$("[data-localize]")
.localize("user", opts1)
.localize("member", opts1)
.localize("etcItem", opts1);
});
but just last pack always loaded.files are together and exist.but always last .localize Line load every time.
what is the matter????
I use plugin with Jquery 1.9 and have an error at the begining.
In my HTML I have added Jquery, plugin and data-localize
In lang I've added json file
In my JS I've added call
var opts = { pathPrefix: "../lang" };
$("[data-localize]").localize("napo", opts);
When I lanch my app I have this error :
[LOG] Error: SyntaxError: JSON Parse error: Unexpected EOF
I don't know if this problem is link to jquery version, but don't understand this error.
Thanks for your help.
Hello,
for HTML5 compatibility it would be fine to use "data-localize" attribute instead of "rel" attribute.
Best regards and thx in advance - also for this fine plugin! :)
Chris
As a developer I would appreciate if the plugin could use parameters so that I don't have to localize any strings with eg. numbers or other constant strings.
In most cases it can be solved by separately localized "span" tags, but in particular cases such as "option" tags you can't. In this case localizing separately each string just because it differs only in the number is waste of space and developers time (not to mention it isn't very elegant).
Example:
Localized JSON
{
my_option: "My option {0}.{1}"
}
HTML:
<select>
<option data-localize="my_option" data-localize-params="1, 1"></option>
<option data-localize="my_option" data-localize-params="1, 2"></option>
<option data-localize="my_option" data-localize-params="2, 1"></option>
<option data-localize="my_option" data-localize-params="2, 2"></option>
<!-- etc. -->
</select>
Result:
Select with options:
My option 1.1
My option 1.2
My option 2.1
My option 2.2
navigator.language
"en-US"
This looks to be an issue w/ how you're detecting the language:
https://github.com/coderifous/jquery-localize/blob/master/src/jquery.localize.coffee#L20
A simple fix to this line would be:
JS
$.defaultLanguage = normaliseLang(navigator.languages? navigator.languages[0] : (navigator.language || navigator.userLanguage));
CS
$.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage)
I'll open a pull-request once I've had a chance to test further!
Is it possible to provide a JSON object instead of file? I just need to download my translations from the database.
Hi,
i'm trying to localize my jquery mobile application with jquery-localize, I followed the steps in https://github.com/coderifous/jquery-localize , I have an exception in jquery-1.9.1 "Uncaught SyntaxError: Unexpected end of input". I tried to resolve it, but the problem still persist.
Now I'm wondering if the plugin works with the jquery version that i'm using.
$("[data-localize]")
.localize("header")
.localize("sidebar")
.localize("footer")
The three json files are all loading correct to the browser. I have three json files which look's like this:
All three json files should replaced with "data-localize". But only the FIRST!! (header-en.json) file will be replaced. The other HTML Tags with "data-localize" are empty.
What do I am wrong ?
The jquery-localize description says, it should be worked in that order as I think.
best regards.
Chris
Hi,
I've recently had an issue regarding the *.json file extension used for the localization files. My web application (SharePoint 2010) hosting your plugin has an http handler defined for this extension and interferes with the plugin... hence, it doesn't work. I've had no other choice but to recode your plugin to use an optional fileExtension option parameter:
...
loadLanguage = function (pkg, lang, level) {
var file,
fileExt = ".json";
if (options.fileExtension) {
fileExt = options.fileExtension;
}
...
It works fine when I use *.js file extensions. Hopefully, you can include this in your next release! ;)
Thanks,
Yohan
We have a problem setting the placeholder of a text input field when the translated text contains non standard chars (for example ü in German translations). I already tried HTML encoding the char(ü) to ü and this works just fine for setting text input values and label values etc. but not for placeholder texts. I use a hidden input control which has the data-localize tag and then after localize function is called I set the placeholder texts by reading this hidden value. But for some reason the placeholder does not seem to decode the encoded text, I also tried setting the ü without encoding but this displays a � char.
what else If we need
<a href="...">...</a>
inside?
Better If this can be allowed.
In some cases, we want the website use a language-country localization json file directly, for example, "zh-CN" (means simplified Chinese) or "zh-TW" (means traditional Chinese).
But the current implementation will first try to load the localization json file with the language code (first two character of the "language" parameter), if it failed, the procedure stops.
For example, if we want to load "message-zh-CN.json", the current implementation will first try to load "message-zh.json", and if it failed, the program stops. This means we must provide an empty "message-zh.json", even if it is useless.
Therefore, the logic of the current implementation should be changed: if the program failed to load the json file with language code, it should continue to try to load the json file with the language-country code.
This issue may have some relation with the issue #22.
Hi.
I use your plugin in an application that can be used locally or hosted in a web server.
I suggest to add an option for local use.
I have modified the code with :
ajaxOptions = {
url: file,
dataType: "json",
/async: false,/
crossDomain: true,
isLocal: true,
timeout: options.timeout != null ? options.timeout : 500,
success: successFunc,
error: errorFunc
};
at the line 71.
Excuse me if I had some mistake with posting suggestion, but it's my first time :)
Have a good day. Alessandra.
"zh-SG", "zh-CN" should fall back to "zh-HANS" (or "zh-CHS")
"zh-TW", "zh-HK", "zh-MO" should fall back to "zh-HANT" (or "zh-CHT")
"zh" is not a valid generic culture.
Hi! A few languages could have 3 characters as iso code. For example, my language Asturian has 3:
ISO 639-2 "ast" or "ast_ES" in browsers.
Please, could you cover these languages too?
Thanks a lot in advance!
I see, inside of plugin code, support for localized images. How work? Thanks :)
I think the plugin should really be cahing the json file something like this...
var fileCache = {};
jsonCall = function (file, pkg, lang, level) {
if (!fileCache[lang]) {
var ajaxOptions, successFunc;
if (options.pathPrefix != null) {
file = "" + options.pathPrefix + "/" + file;
}
successFunc = function (d) {
$.extend(intermediateLangData, d);
notifyDelegateLanguageLoaded(intermediateLangData);
return loadLanguage(pkg, lang, level + 1);
};
ajaxOptions = {
url: file,
dataType: "json",
async: false,
timeout: options.timeout != null ? options.timeout : 500,
success: successFunc
};
if (window.location.protocol === "file:") {
ajaxOptions.error = function (xhr) {
return successFunc($.parseJSON(xhr.responseText));
};
}
fileCache[lang] = $.ajax(ajaxOptions);
}
return fileCache[lang];
};
I dont know coffee otherwise i would submit a pull
Hello it's possible to re-initialize the localize after a request ajax complete or load event?
example not working
$(document).ajaxStop(function(){
var opts = { language: "en", pathPrefix: "/" };
$("[data-localize]").localize("shop", opts);
});
Synchronous request are now deprecated. Would it be possible to change the ajax request loading the translation files and do it asynchronously?
Then it would be nice to have a cache mechanism to store the translations in memory and thus avoid the asynchronous call if the data was already loaded once.
See warning from Google Chrome:
"Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
Hi.
I am testing out this library and it seems to be perfect for my use. I just have one little problem. When I translate to a language that does not exist, the default values are used instead. But when I translate to a language where a language file exists, but not all the keys, the default value is ignored and a empty value is inserted instead. Is there a way to force the default values to be used instead of an empty string?
Hi, just wondering if its possible to localize video parameters?
<object id="vid1">
<param name="bgcolor" value="#FFFFFF" data-localize="video.bgcolor" />
My UI uses option groups in drop downs and I would like to be able to localize the labels.
I could do this with a custom callback but I propose that this is a reasonable thing for the default callback to handle. Handling the optgroup would require adding (essentially...) :
tag = elem.attr('tagName');
....
else if (tag === 'OPTGROUP') {
elem.attr('label', value);
}
I think this is a better option than reimplementing the default callback as a custom cb (with the simple addition). The other option would be to scan for the optgroups in a custom cb and "fallthrough" to the default but, this would iterate the wrappedset twice which would not be good.
I made a small test and noticed that it only works when run on Firefox on Windows 8.1. When using IE or Crome the library crashes. I cannot even run the test cases you provide but almost all tests fail.
Hi,
Why isn't there a fallback error that handles the case where a localization file isn't found? For example, if my locale is set to "en-CA" but I only have a "en" json file, it will try to fetch the "en-CA" file and fail.
Thanks
Yohan
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.