a jQuery plugin that makes it easy to internationalize your web site.

Overview

jquery.localize.js

Build Status

A jQuery plugin that makes it easy to i18n your static web site.

Synopsis

  • Lazily loads JSON translation files based on a simple naming convention.
  • By default, applies the translations to your document based on simple attribute convention.
  • Tested with jQuery versions 1.7.2, 1.8.3, 1.9.1, 1.10.2, 1.11.3, 2.0.3, 2.1.4

Getting Started

Download the production version or the development version.

Load the jquery-localize plugin on your page.

It's the file located at dist/jquery.localize.js

Mark up tags whose content you want to be translated

Somewhere in your html:

<h1 data-localize="greeting"> Hello! </h1>

Provide a JSON language file that has translations:

example-fr.json:

{
  "greeting": "Bonjour!"
}

Use the localize plugin.

<script>
// In a browser where the language is set to French
$("[data-localize]").localize("example")

// You can also override the language detection, and pass in a language code
$("[data-localize]").localize("example", { language: "fr" })
</script>

Gory Details

Language file loading

The first argument of the localize method is the name of the language pack. You might have a different language pack for different parts of your website.

Here's an example of loading several language packs:

<script>
$("[data-localize]")
    .localize("header")
    .localize("sidebar")
    .localize("footer")
</script>

If the language of the browser were set to "fr", then the plugin would try to load:

  • header-fr.json
  • sidebar-fr.json
  • footer-fr.json

if the language of the browser also had a country code, like "fr-FR", then the plugin would ALSO try to load:

  • header-fr-FR.json
  • sidebar-fr-FR.json
  • footer-fr-FR.json

This let's you define partial language refinements for different regions. For instance, you can have the base language translation file for a language that translates 100 different phrases, and for countries were maybe a some of those phrases would be out of place, you can just provide a country-specific file with just those special phrases defined.

Skipping Languages (aka Optimizing for My Language)

This is useful if you've got a default language. For example, if all of your content is served in english, then you probably don't want the overhead of loading up unecessary (and probably non-existant) english langauge packs (foo-en.json)

You can tell the localize plugin to always skip certain languages using the skipLanguage option:

<script>
//using a string will skip ONLY if the language code matches exactly
//this would prevent loading only if the language was "en-US"
$("[data-localize]").localize("example", { skipLanguage: "en-US" })

//using a regex will skip if the regex matches
//this would prevent loading of any english language translations
$("[data-localize]").localize("example", { skipLanguage: /^en/ })

//using an array of strings will skip if any of the strings matches exactly
$("[data-localize]").localize("example", { skipLanguage: ["en", "en-US"] })
</script>

Applying the language file

If you rely on the default callback and use the "data-localize" attribute then the changes will be applied for you.

Examples:

HTML:

<p data-localize="title">Tracker Pro XT Deluxe</p>
<p data-localize="search.placeholder">Search...</p>
<p data-localize="search.button">Go!</p>
<p data-localize="footer.disclaimer">Use at your own risk.</p>
<p data-localize="menu.dashboard">Dashboard</p>
<p data-localize="menu.list">Bug List</p>
<p data-localize="menu.logout">Logout</p>

application-es.json (fake spanish)

{
  "title": "Tracker Pro XT Deluxo",
  "search": {
    "placeholder": "Searcho...",
    "button": "Vamos!"
  },
  "footer": {
    "disclaimer": "Bewaro."
  },
  "menu": {
    "dashboard": "Dashboardo",
    "list": "Bug Listo",
    "logout": "Exito"
  }
}

Localize it!

<script>
$("[data-localize]").localize("application", { language: "es" });
</script>

Callbacks

You can provide a callback if you want to augment or replace the default callback provided by the plugin. Your callback should take at least 1 argument: the language data (contents of your json file). It can optionally accept a second argument, which is a reference to the default callback function. This is handy if you still want the default behavior, but also need to do something else with the language data.

<script>
$("[data-localize]").localize("application", {
    language: "es",
    callback: function(data, defaultCallback){
        data.title = data.title + currentBugName();
        defaultCallback(data)
    }
});
</script>

See the test/samples for working examples.

Contributing

To contribute to this plugin, please read the contributing guidelines.

Credits & Licensing

Copyright (c) Jim Garvin (http://github.com/coderifous), 2008.

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 Jim Garvin (@coderifous) for use on LMGTFY.com. Please use it, and contribute changes.

http://github.com/coderifous/jquery-localize

Based off of Keith Wood's Localisation jQuery plugin. http://keith-wood.name/localisation.html

Comments
  • Synchronous XMLHttpRequest warning

    Synchronous XMLHttpRequest warning

    Hi,

    I get the following warning when implementing the plugin with $( '[data-localize]' ).localize( 'content' );:

    Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

    Can anybody help out how to avoid that?

    opened by magglomag 7
  • Manually load 'string'

    Manually load 'string'

    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...

    opened by Toverbal 7
  • Revert back to original translation

    Revert back to original translation

    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!

    opened by edwardmp 7
  • Jquery mobile a href and buttons issues

    Jquery mobile a href and buttons issues

    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

    opened by i-vision 6
  • Localizing element attributes

    Localizing element attributes

    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

    opened by yohanb 6
  • Load files asynchronously and cache them

    Load files asynchronously and cache them

    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/."

    opened by zoulou2356 5
  • Doas jquery-localize works with jquery-1.9.1 ?

    Doas jquery-localize works with jquery-1.9.1 ?

    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.

    opened by redamimouni 5
  • Synchronous XMLHttpRequest

    Synchronous XMLHttpRequest

    Synchronous XMLHttpRequest on the main thread are being deprecated because of its detrimental effects to the end user's experience. Recent browser versions are deprecating jQuery's async flag. It would be good thing to remove them.

    screen shot 2015-07-28 at 12 56 23

    opened by ivoputzer 4
  • Load 3 data-localize json files

    Load 3 data-localize json files

    $("[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:

    1. header-en.json { "nav": { "assignmentchart": "Belegungsplan" } }
    2. sidebar-en.json { "sidebar": { "test": "test" } }
    3. footer-en.json { "footer": { "abc": "testtest" } }

    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

    opened by ChrisFeldmeier 4
  • fix android quirks (navigator.languages is empty on Android >= 5.0)

    fix android quirks (navigator.languages is empty on Android >= 5.0)

    Hi,

    I encountered an issue on Cordova + jQuery + jquery-localize on Android 5.0 and up (confirmed on 5.0 / 5.1 / 6.0 AVD emulators). I guess it is the same issue as issue #72.

    This issue happens when navigator.languages returns an empty array [] although navigator.language itself contains a value. Seems like it's happening on Android 5.0 and up (see also: “navigator.languages is empty in webview”)

    In line 20 of src/jquery.localize.coffee, the argument for normalizeLang() is (unexpectedly) set to undefined:

    $.defaultLanguage = normaliseLang(if navigator.languages then navigator.languages[0] else navigator.language or navigator.userLanguage)

    then in the line 14, it fails with the message "Uncaught TypeError: Cannot read property 'replace' of undefined".

    So here's the fix for this, ensuring navigator.languages is not empty:

    $.defaultLanguage = normaliseLang(if navigator.languages and navigator.languages.length > 0 then navigator.languages[0] else navigator.language or navigator.userLanguage)

    I believe this trivial patch has no side effect (for older Android versions / iOS / other browsers).

    opened by shaolin405mi16 3
  • Localize not working in Cordova app on Android 6.0

    Localize not working in Cordova app on Android 6.0

    I have an app that I am building using cordova, and it uses jquery localize to switch between various JSON files in order to show my pages in different languages. The functionality works fine on the web, in iOS, and in previous versions of android. But after upgrading one of my test devices to Android 6.0, the buttons to switch languages no longer work. I hooked up the phone to adb and got this output while debugging:

    Here is the error that it throws when the app is first loaded:

    03-14 11:51:02.702 27974-27974/? I/chromium﹕ [INFO:CONSOLE(4)] "Uncaught TypeError: Cannot read property 'replace' of undefined", source: file:///android_asset/www/app/vendor/jquery-localize-i18n/dist/jquery.localize.js (4)

    And here is the error that it throws every time you click on one of the language buttons:

    03-14 11:51:48.323 27974-27974/? I/chromium﹕ [INFO:CONSOLE(469)] "Uncaught TypeError: $(...).localize is not a function", source: file:///android_asset/www/app/js/arkeo-functions.js (469)

    The relevant section of code that it's referencing is the LocalizeThis function from arkeo-functions.js Here it is: function localizeThis(lang) { $('#checkLang em').removeClass("fa-check"); $('#checkLang em').addClass("fa-fw"); $('.' + lang + ' em').addClass("fa-check");
    $("[data-localize]").localize("i18n/site", { language: lang });
    localStorage.setItem('jq-appLang', lang); } I checked and it seems that there may be one other person having this issue with the jquery.localize plugin, but it's very recent and hasn't been resolved.

    Beyond this info, I'm not sure what to do. The functionality still works on the web, in iOS, and on older versions of Android. I can't for the life of me figure out what changed. After exhaustively looking into the whitelist plugin as well as content security policies, I don't think that's it at all.

    Any insights you have would be super helpful.

    opened by ArkeoSupport 3
  • Using localize with icons

    Using localize with icons

    How can i use jquery-localize with my icons? They are stored inside the 2 html tags. Means

    <a href="/gallery" data-localize="navbar.gallery">Gallery <i class="material-icons right>image</i></a>

    so it gets replaced with just "Gallery" and not "<i class ...", so the icon is missing.. Just putting the "" within the locale json file also doesnt work. (The translation stops working completely when i do this)

    opened by lollilol 0
  • Callback not working with Phonegap + Onsen UI

    Callback not working with Phonegap + Onsen UI

    I am developing a hybrid app with Phonegap and Onsen UI. My console shows me that the language file has been correctly loaded, but the localization does not appear. After several tries, i used the example with the callback from this Github repo together with a simple alert AND a console.log - but nothing happens.

    This is my code so far:

    var opts = { language: "de", pathPrefix: "/js", skipLanguage: "en-US" }; opts.callback = function(data, defaultCallback) { data.message = "Optional call back works."; $("[data-localize]").css({color: "#FF8833"}); defaultCallback(data); alert("this is an alert for the callback"); console.log("the callback console logger."); } $("[data-localize]").localize("lang", opts)

    I have a CSP Meta-Tag that should allow everything (also load local JSON files, afaik). It looks like this: ` meta http-equiv="Content-Security-Policy" content=" default-src 'unsafe-eval' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; worker-src blob:; style-src 'self' 'unsafe-inline' *; img-src 'self' 'unsafe-inline' 'unsafe-eval' *"

    I am sure that i am missing some privileges somewhere, but i am not able to find the error.`

    opened by qroft 2
  • default fallback

    default fallback

    Is there a simple way to set the default/fallback language file to use. For example if the user sets their browser to German but there isn't a German language file I would like it to use the English language file. A lot of my page content is loaded dynamically using the $.localize.data object.

    Basically what I need is someway to say, if there is no German file use the English one.

    opened by davidhealey 0
  • How to customize the jquery.localize.js file to pass different languages

    How to customize the jquery.localize.js file to pass different languages

    Thanks for your link.This helped me a lot!

    Instead of the internet browser detecting the language and user changing it,is there any way to customize the jquery.localize.js file and pass our customized language onto the file. Please help me with any sample project or link.This will helps us to continue with our r&d development .

    with love, sreedhar

    opened by getsreedharpv 1
  • get string from javascript

    get string from javascript

    hi, i put this code in my page: var opts = { language: "en-GB", pathPrefix: "../localize", skipLanguage: "default" }; $("[data-localize]").localize("lang", opts);

    it's possible to get the string from json file?

    I tried with:

    console.log($.localize.data["localize/lang"]["title"]);

    but not working!

    any help?

    br Max

    opened by maxdiable 0
Owner
Jim Garvin
Jim Garvin
Powerful, intelligent and easy to use Figma internationalisation scripts

Powerful, intelligent and easy to use Figma internationalisation scripts English | 中文 ?? Script Installation Before installing the Figma I18n script,

Afeyer 138 Dec 10, 2022
🌐jQuery based internationalization library

jQuery.i18n NOTE: For jquery independent version of this library, see https://github.com/wikimedia/banana-i18n jQuery.i18n is a jQuery based Javascrip

Wikimedia 649 Jan 4, 2023
:globe_with_meridians: Internationalization plugin for Vue.js

vue-i18n Internationalization plugin for Vue.js ?? Gold Sponsors ?? Silver Sponsors ?? Bronze Sponsors ⚠️ NOTICE This repository is for Vue I18n v8.x.

kazuya kawaguchi 6.9k Dec 29, 2022
Give your JavaScript the ability to speak many languages.

Polyglot.js Polyglot.js is a tiny I18n helper library written in JavaScript, made to work both in the browser and in CommonJS environments (Node). It

Airbnb 3.6k Jan 2, 2023
Code for How to Internationalize (i18n) a React App with Transifex

Code for How to Internationalize (i18n) a React App with Transifex Code for How to Internationalize (i18n) a React App with Transifex Tutorial Prerequ

Shahed Nasser 2 Dec 15, 2022
[DISCONTINUED] jQuery plugin that makes it easy to validate user input while keeping your HTML markup clean from javascript code.

jQuery Form Validator [DISCONTINUED] Validation framework that let's you configure, rather than code, your validation logic. I started writing this pl

Victor Jonsson 976 Dec 30, 2022
jBox is a jQuery plugin that makes it easy to create customizable tooltips, modal windows, image galleries and more.

jBox jBox is a jQuery plugin that makes it easy to create customizable tooltips, modal windows, image galleries and more. Demo: https://stephanwagner.

Stephan Wagner 1.4k Dec 15, 2022
:clock8: The original jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago").

timeago: a jQuery plugin Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "ab

Ryan McGeary 3.8k Dec 25, 2022
A Browser extension that not only makes your browsing experience safe but makes it optimized

Sia Sia is a browser extension that not only makes your browsing experience safe but makes it optimized Table of Contents About The Project Built With

Arun Govind M 14 Feb 23, 2022
A JavaScript module that shortens your code, makes life easier, and makes development faster!

Quxt A JavaScript module that shortens your code, makes life easier, and makes development faster! Installation npm install quxt Quick Start Check ind

Qux App 5 May 8, 2022
An easy to implement marquee JQuery plugin with pause on hover support. I know its easy because even I can use it.

Simple-Marquee Copyright (C) 2016 Fabian Valle An easy to implement marquee plugin. I know its easy because even I can use it. Forked from: https://gi

null 16 Aug 29, 2022
jQuery plugin that makes an image erasable (with mouse or touch movements)

jQuery.eraser v0.5.2 a jQuery plugin that makes an image erasable (with mouse or touch movements) This plugin replaces the targeted image by an intera

boblemarin 327 Oct 27, 2022
A jquery plugin that makes images truly responsive, without sacrificing anyone's face. Give it more stars!

Responsify.js A jquery plugin that makes images truly responsive, without sacrificing anyone's face :D When images are used in a responsive container

Wenting Zhang 1.3k Dec 14, 2022
Jaxit is an easy-to-use library that makes an interactive terminal for your programs.

Jaxit Jaxit is an easy-to-use library that makes an interactive terminal for your programs. Jaxit was made by Codeverse, so check on Codeverse's Profi

null 3 Dec 11, 2022
A JSON Database that saves your Json data in a file and makes it easy for you to perform CRUD operations.

What is dbcopycat A JSON Database that saves your Json data in a file and makes it easy for you to perform CRUD operations. ⚡️ Abilities Creates the f

İsmail Can Karataş 13 Jan 8, 2023
Buildable's core open-source offering for actions that makes it easy to collect, centralize and action your backend system activity

What are Action Templates? Action Templates are open-source functions that save developers hundreds of hours when integrating databases, apps and othe

Buildable 6 Nov 5, 2022
A crawler that crawls the site's internal links, fetching information of interest to any SEO specialist to perform appropriate analysis on the site.

Overview ?? It is a module that crawls sites and extracts basic information on any web page of interest to site owners in general, and SEO specialists

Yazan Zoghbi 2 Apr 22, 2022
A crawler that crawls the site's internal links, fetching information of interest to any SEO specialist to perform appropriate analysis on the site.

Overview ?? It is a module that crawls sites and extracts basic information on any web page of interest to site owners in general, and SEO specialists

Yazan Zoghbi 2 Apr 22, 2022
Easily publish notes to the web This plugin integrates with obsius.site to publish markdown notes on the web.

Obsius Publish Easily publish notes to the web This plugin integrates with obsius.site to publish markdown notes on the web. Limitations The type of c

Jon Grythe Stødle 66 Dec 20, 2022