Lokalizr

HTML5, CSS3 and JavaScript Experiments and Insight Website

Try Semtex – the new HTML5, CSS3 and JavaScript UI framework!

I am pleased to announce that I’ve just finished my latest endeavour – HTML5, CSS3 and JavaScript Experiments and Insight, and most of the code samples and demos from my blog have been moved there in and new and convenient code-listing and demo form. From now on, each new blog post will be accompanied by a dedicated page on that website on which my readers will be able to have a look at the code, run the example and eventually download it.

Enjoy HTML5, CSS3 and JavaScript Experiments and Insight and have a great rest of the week!

Advertisements

Useful JavaScript Classes and Functions

  • Crossbrowser image reflections enabler JavaScript class.
  • JavaScript Mapper Class for RESTFul Methods – Recently I had to work with a bunch of RESTFul API methods, so instead of defining manually separate calls/methods for each API request, I decided to do it viceversa – to force JavaScript to create these methods automatically for me out of the RESTFul API by providing the URLS and other required data.
  • XML to JSON JavaScript Objectifier Class – Simple XML to JSON objectifier. It can be used with custom or public XML, REST APIs such as Last.FM, RSS and ATOM feeds, sitemaps, etc by converting the XML server responses to native JSON objects in the browser which are then instantly accessible by its simple to use JavaScript methods.
  • URI to JSON Serializer Class – Tiny JavaScript class, using the HTMLAnchorElement interface to convert URI string into a JSON object.  The object returned by the function contains hash, host, hostname, parameters key-value map, pathname, port and protocol. Works with all major browsers (Firefox, Chrome, Safari, Opera, IE6-10).
  • IMDB Fetcher – Experimental IMDB JavaScript and PHP API – Makes possible the execution of cross-domain AJAX queries to IMDB and returns a JSON data object for the requested movie. What is currently supported – movie title, poster, release date, description, actor(s), director(s), IMDB and MPAA rating, running time, etc.
  • Quick and Dirty Localization With JavaScript – A quick and dirty JavaScript localization routine that provides basic localization (no support for plurals, etc), operates on the DOM of the page and uses data-lang attribute for language keys storage. Lokalizr works with all major browsers, beginning with IE8.
  • JavaScript Instance Name Finder – Small JavaScript function that checks for instances of an object within a defined scope and returns an array of instances’ variable names that can be used for different purposes.
  • HTML5 Placeholder Enabler – The solution presented in this post checks for the availability of the placeholder attribute in textboxes, and if it is not available applies its content as value to the elements that contain it.
  • HTML 5 Details Element Enabler – According to WhatWG, the “<details /> element represents a disclosure widget from which the user can obtain additional information or controls“. In brief, you can use it to create panelbar elements without JavaScript, as the expand / collapse functionality is native to it. Currently (October, 2011), the only browser which supports <details /> is Google Chrome, so if you are eager to start using this element on your pages, you can do so with the help of a few lines of JavaScript to make sure it works on all browsers.
  • WebWorkers JavaScript class.
  • Classless JavaScript inheritance.
  • JavaScript class augmenter.
  • JavaScript API for TinyURL.
  • HTML Validation Bookmarklet.
  • JavaScript Template Engine.

Quick and Dirty Localization With JavaScript

Here’s a quick and dirty JavaScript localization routine that provides basic localization (no support for plurals, etc) , operates on the DOM of the page and uses data-lang attribute for language keys storage. Lokalizr works with all major browsers, beginning with IE8. If you do not want to read the code below, you can just download and test the class from this link.

The Lokalizr JavaScript Class:

(function() {
    "use strict";

    /*
     * @class Lokalizr
     * @constructor Lokalizr
     * @param languages {Object} [required]
     * @param defaultLanguage {String} [optional]
     **/
    function Lokalizr(languages, defaultLanguage) {

        this.languages = languages || {};

        if(defaultLanguage) {
            this.localize(defaultLanguage);
        }
    }

    Lokalizr.prototype = {

    /*
     * @map ATTR
     * @public
     **/
    ATTRS: {
        lang: "data-lang"
    },

    /*
     * @map MESSAGES
     * @public
     **/

    MESSAGES: {
        invalid: "Invalid language code."
    },

    /*
     * @method localize
     * @public
     * @param langCode {String} [required]
     **/
    localize: function(langCode) {
        if(false === "querySelectorAll" in document) {
            return;
        }

        var
            lang = this.languages[langCode],
            attr = this.ATTRS.lang,
            elements = document.querySelectorAll("[" + attr + "]");

        if(!lang) {
            this.error(this.MESSAGES.invalid);
            return;
        }

        for(var i = 0, len = elements.length; i < len; i++) {
            var
                element = elements[i],
                key = element.getAttribute(attr);

            element.innerHTML = lang[key];
        }
    },

    /*
     * @method getLangString
     * @public
     * @param langCode {String} [required]
     * @param langString {String} [required]
     * @return {String}
     **/
    getLangString: function(langCode, langString) {
        if(langCode && langString) {
            return this.languages[langCode][langString];
        }
    },

    /*
     * @method error
     * @public
     * @param message {String} [required]
     **/
    error: function(message) {
        window.alert(message);
    }
};

    window.Lokalizr = Lokalizr;
})();

Example Markup:

<p data-lang="hello">Hello</p>
<p data-lang="good-morning">Good Morning</p>
<p data-lang="good-evening">Good Evening</p>

Usage:

(function() {
    // instantiate Lokalizr and localize automatically
    window.lang = new window.Lokalizr({
        "en-US": {
            "hello": "Hi",
            "good-morning": "Good morning",
            "good-evening": "Good evening"
        },
        "de-DE": {
            "hello": "Hallo",
            "good-morning": "guten Morgen",
            "good-evening": "guten Abend"
        }
     } , "de-DE");

     // localize on demand
     window.lang.localize("en-US");

     // get specific language keys
     window.console.log("language string",
         window.lang.getLangString("de-DE", "hello"));
     window.console.log("language string",
         window.lang.getLangString("de-DE", "good-morning"));
     window.console.log("language string",
         window.lang.getLangString("de-DE", "good-evening"));
 })();

That’s it! Did you check the demo?.

Enjoy the weekend!

Related Posts