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"); = "0 0 0 0"; = "0 0 0 0";
    // = "start"; // If CSS 3+ = ""; // Explicitly override text align that might be assigned via style sheets
    var span = document.createElement("span");
    span.innerHTML = "X";
    // 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" : 

    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.

Retrieving Inherited CSS Styles with DOM

If you need to get a CSS style from an element in a document, you cannot just test the style of the element directly. That is: won’t work. Take this example:

<p style="white-space:pre">
  Hello world - <b> A  B  C  D </b>

The immediate white space style of the bold element in the DOM will be normal (default for bold element). However the style is actually pre, since it inherits it from the paragraph ancestor element.
Continue reading