Jquery – Creating a general language file to declare defaults for any plugins
Question by denislexic
Like most people, I use a bunch of jquery plugins on my website. From Twitter bootstrap to jquery ui datepicker and so on.
But I need my website to be multilingual, so I created a general language file called english.js , and in that file I want to declare some of the defaults from plugins as well as other language variables.
The problem is that all these plugins have varying structures to declare defaults. I saw a couple of questions already ( jquery – setting plugin defaults?, Globally defining jQuery plugin parameters , jQuery plugin defaults , …). But they are not clear.
STRUCTURE 1
$.fn.ajaxStatus = function (params)
{
var settings = $.extend(
{
defaultLoadingText :"Loading...",
defaultSavingText :"Saving...",
defaultDoneText :"Done",
defaultRedirectText:"Redirecting...",
defaultErrorText :"Oops! Our bad, something wrong.";
},$.fn.ajaxStatus.defaults,
params),
});
STRUCTURE 2
jQuery.fn.extend({
shrinker:function (options) {
var opts = $.extend({
"moreText":"Read more",
"lessText":"hide",
}, $.fn.shrinker.defaults, options);
});
THE QUESTION
Without modifying the plugin, is it possible to assign some defaults for the function that will be used every time I use the plugin?
How can I define the language defaults in an external file?
Right now, I have this in my language file, but it feels wrong, is this how you do it?
if ($.fn.ajaxStatus !== undefined) {
$.fn.ajaxStatus.defaults =
{
defaultLoadingText :"Loading2...",
defaultSavingText :"Saving2...",
defaultDoneText :"Done2",
defaultRedirectText:"Redirecting2...",
defaultErrorText :"Oops! Our bad, something wrong"
};
}
Thanks in advance for you help.
Answer by Starx
I have done somehow similar to this. But I am not giving the full implementation.
Here is how to do it.
Define your plugins params for language like this:
var options = {
lang: "np" //your default language
};
Set up your language objects like this
var lang = {
"en": {
"var1" : "This is variable one"
},
"np": {
"var1": "यो एउटा भेरियबल हो ।" //Different text based on language initials
}
};
Then you can simply create a function to read the value like this
function showVar1() {
alert(lang[options.lang].var1);
}
[Demo]Its not a plugin based.