Giter Club home page Giter Club logo

jquerytranslator's Introduction

#jqueryTranslator

jqueryTranslator is a jQuery plugin which allows developers to translate a static web site easily.

  1. It first loads asynchronously the translation files you supply to the plugin. It can be a string or an array of them.

  2. Then, it translates the element based on the user's browser language. The plugin is able to translate the text of the element or change attributes, or even both!

  3. Finally, if you supply a callback, it will be executed over every element to be translated.

Now you can see a demo.

Usage & Documentation

Just include one of the plugin files in your file.

Use the "data-translate" attribute on DOM elements you want to be translated

    <h1 data-translate="hello"> Hello! </h1>
    <img data-translate="img" alt="This is an image!" src="someimage.jpg" />

The "hello" and "img" words serve as sort of key so it's easier to locate the translation.

Create a JSON language file with the translations:

index-es.json:

    {
      "hello": "Hola!"
      "img" : "Esto es una imagen!"
    }

Call the plugin!

$("[data-translate]").jqTranslate('index');

In-depth explanation and Documentation

The first argument the plugin receives, is the package that it has to load. You may have different packs for different parts of the website (header, dialogs, etc);

You can load more than one package like this:

    $("[data-translate]").jqTranslate(['index', 'header', 'footer']);

If the language of the user's browser is "es", the plugin will try to load:

  • index-es.json
  • header-es.json
  • footer-es.json

If the language also has a country code, like "es-MX", the plugin will ALSO try to load the following:

  • index-es-MX.json
  • header-es-MX.json
  • footer-es-MX.json

This can provide you more customization for different regions. Unfortunately, most of current browsers (desktop) only have the language portion though mobile ones use to have both.

Options

An object containing parameters. Please, note that all parameters are optional.

asyncLangLoad (boolean): Whether if the language should be loaded asynchronously or syncrhonously. Default: true (asynchronously)

cache (boolean): Whether if the language packages should be cached or not. Default: true

defaultLang (string): The default language of the Application, this language won't be loaded. Default: null

fallbackLang (string): String that sets a fallback language to load in case it can't load the user language. Default: null

forceLang (string): String that forces the language for the script, forgetting the user's language. Default: null

path (string): This is the default path of the translation files. Useful if you want to locate your files in a separated folder. Default: null

onComplete (function): Callback function triggered when a DOM element has been translated. this will point to the element.Default: null

skip (array of strings): An array containing all the languages you want to avoid the translation. Default: empty array

Advanced

Here are some advanced tricks you can use and some extra info.

First, let's see how the plugin reacts to the elements:

input : It first checks if it's a placeholder and, if it is, it translates it. If it doesn't it will change the input value to one supplied.

optgroup : Get their label attribute translated

img : Get their alt attribute translated

default : Get their HTML replaced.

Changing multiple attributes for each element

If the key for a given value contains nested values, it will try change them all. Please, have in mind that you are responsible of supplying the correct attributes. For example:

index-es.json:

    {
      "hello": "Hola!"
      "img" : {
      	"text" : "Esto es una imagen!",
      	"src" : "linktootherimage.jpg"
      }
    }

The text attribute will replace the normal behaviour and will follow the aforementioned rules to translate the element. The remaining attributes will be directly changed on the element.

FAQ

How can I translate my jQuery Mobile application?

Using jQuery Mobile 1.1 and further

$(document).on('pagecreate','#home',function(event){
      $("[data-translate]").jqTranslate('index', { asyncLangLoad: false });
});

Pre jQM 1.1

$('#home').live('pagecreate',function(event){
      $("[data-translate]").jqTranslate('index', { asyncLangLoad: false });
});

Where #home is the ID of the page.

Also, have in mind that you may need to refresh the page element in order to be displayed correctly. Please, head to the jQuery Mobile documentation to have more info about those methods.

My page isn't being translated!

The most common cause of this, is because the JSON package isn't valid. To check it, please use some kind of validation service such as JSONLint.

Contributing

You are invited to contribute code and make suggestions to this project. If you're interested in contributing, please fork the repository, make your changes, and send a pull-request.

Also, consider submitting your own's language localization and I'll include them in the demo page!

Learn more about how to fork and pull-requests.

Credits & Licensing

Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses.

Written by Antonio Laguna (@Belelros) Please use it, and contribute changes.

Based on Jim Garvin's Localisation jQuery plugin. https://github.com/coderifous/jquery-localize

jquerytranslator's People

Contributors

antonio-laguna avatar leon-anavi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquerytranslator's Issues

textarea placeholder doesn't work

Hi there

while the placeholder in the input works perfectly:

If we use the textarea instead, the translated text appears as the value of the textarea, not as the placeholder.

<textarea name="message" id="message" placeholder="Escribe un mensaje" data-translate="write-message"></textarea>

Could u please check this issue?
Thanks!

demo-es-ES.json isn't working

Hi !!!
Im testing the plugin and it's working fine with my demo-es.json file, but now I'm trying to load a demo-es-ES.json file and it doesn't translate the page, I alert the language in the plugin and it's es-ES ... what I'm losing ? ... in page documentation says that it will search demo-es-ES.json format too. But I don't know why It doesn't work ?
I'm using jquery-1.9.0.min.js and latest github version of jqueryTranslator.js

And I'm initializing with this function

<script> (function(){ $("[data-translate]").jqTranslate('demo'); })(); </script>

thanks.

Tilde on placeholder

When you translate a placeholder, and use like &etilde; is printing like that and not the supposed character.

Switching back to no language file on click

Hi,

I am using the plugin in a language switcher. My default language is German (the German strings are in my index.html like <h1 data-translate="title">Title in German</h1>) and I have a language file content-en.js for the English translation.

The language can be switched on click:

    $buttonEN.click(function( e ) {
      $( '[data-translate]' ).jqTranslate( 'content', { forceLang: 'en' });
    });

What I now like to achieve is that when I click on $buttonDE not the German language file should be loaded but the normal strings in my index.html. So is there a function to just stop the plugin from loading a language file?

    $buttonDE.click(function( e ) {
      /* The regular strings in my `index.html` should be loaded. */
    });

Thanks for your help!

I seem to have met a BUG

My browser language is zh-CN, it successfully loaded the /languages/common-zh-CN.json file.
But console display the following error:

image

Alert messages Translation

Hi,
I would like to know if its possible to translate messages used in a javascript alert function. Or do i have to use HTML, decorate a div and read that div in the javascript ?

Any suggestion,
Yamil

Use of sessionStorage

If the plugin is used in different pages, every time there is an ajax request to get the data from the json dictionary.
Wouldn't be interesting to use sessionStorage to save the data and only make an ajax call the first time?

My proposal would be something like this:

   getLanguage : function(pkg, language){
        var loaded = 0, maxLoad = Translate.languages.length * Translate.packages.length;
        var self = this, url = '';
        if (self.options.path){
            url = self.options.path + '/';
        }
        url += [pkg, language].join('-') + '.json';
        if (sessionStorage["dict_"+language]) {
            Translate.storeLangFile(JSON.parse(sessionStorage["dict_"+language]));
            Translate.loaded.resolve();
        } else {
                return $.ajax ({
                    url : url,
                    dataType : "json",
                    cache : self.options.cache,
                    async: self.options.asyncLangLoad,
                    success: function(data) {
                        sessionStorage["dict_"+language] = JSON.stringify(data);
                        Translate.storeLangFile(data);
                    },
                    complete: function(){
                        loaded++;
                        if (loaded >= maxLoad) Translate.loaded.resolve();
                     }
                }
                );
         }
    },

Thanks!

I have an error with forceLang

I am trying in various ways but putting forceLang the plugin does not perform most of the page translation.

this is my code :
if(lang_salvata == '') $("[data-translate]").jqTranslate('', { defaultLang : "en", path : 'languages/index'}); else $("[data-translate]").jqTranslate('', { path : 'languages/index', forceLang : lang_salvata});

what am I doing wrong?

Attach transaltion to and event

So I'm attaching the plugin call to Change event in a select with values (en, fr, es)

The first call is good and the plugin actually does the translation, but the calls later doesn't do anything, no errors on console, nothing.

Is there a specific way to do this ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.