Inferring the Locale text direction with Javascript

Here’s a hack to detect which is the locale text direction (e.g. left-to-right for English or right-to-left for Hebrew) using JavaScript:

/**
 * Detects locale text direction...
 * @return {String} "ltr" or "rtl"
 */
function detectTextDir() {
   var container = document.createElement("p");
    container.style.margin = "0 0 0 0";
    container.style.padding = "0 0 0 0";
    // container.style.textAlign = "start"; // If CSS 3+ 
    container.style.textAlign = ""; // Explicitly override text align that might be assigned via style sheets
    
    var span = document.createElement("span");
    span.innerHTML = "X";
    
    container.appendChild(span);
    document.body.appendChild(container);
    
    // LTR if text position is nearer left of container, RTL if text position is nearer right of container
    var localeDirection = span.offsetLeft < (container.offsetWidth - (span.offsetLeft + span.offsetWidth)) ?
        "ltr" : 
        "rtl";
       
    document.body.removeChild(container);

    return localeDirection;
}

A limitation is that it doesn’t work if there is a style sheet present which explicitly assigns a text-align value other than “start” for paragraphs directly in the document body. You could probably tweak the idea to use something more obscure like an address block to reduce chances of this happening.

Advertisements

3 thoughts on “Inferring the Locale text direction with Javascript

  1. I am working on an open source JavaScript library for the HTML5 canvas tag and would like to adapt the code above for use in a hit test function. The library will be released under the LGPL () but in future I may want to move over to the MIT license ().

    Would you be willing to release the code above under one or (preferably) both of those licenses? Obviously, you would appear on the list of contributors to the work and your code would be clearly indicated within the library’s source.

  2. Great, thanks. Thanks.

    Email me with your real name (or a pseudonym) and I’ll add it to the list of contributors. (I assume you can see my email.)

    The lib is nearly ready but there’s one or two things left to tidy up. I’ll email you a link when it’s done.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s