Search code examples
javascripthtmlcssinternationalizationright-to-left

use text-align smartly (if english dir=ltr if arabic dir=rtl)


I have a community web site and I want that users write

  • English posts with direction LTR / text-align: left) and
  • Arabic posts with direction RTL / text-align: right.

E.g. Google+ and twitter provides such an POST solution.

I want add automatically direction attribute to post when i read it from data base post load in rtl or ltr ! but i don't know how ?!


Solution

  • You'll need to create a function that has all the letters you know are RTL and check when loading. To display RTL you need the CSS attributes, direction, text-align, and unicode-bidi.

    Demo: jsFiddle

    Script

    function checkRtl( character ) {
        var RTL = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
        return RTL.indexOf( character ) > -1;
    };
    
    var divs = document.getElementsByTagName( 'div' );
    
    for ( var index = 0; index < divs.length; index++ ) {
        if( checkRtl( divs[index].textContent[0] ) ) {
            divs[index].className = 'rtl';
        } else {
            divs[index].className = 'ltr';
        };
    };
    

    CSS

    .rtl {
        direction: rtl; 
        text-align: right;
        unicode-bidi: bidi-override;
    }
    
    .ltr {
        direction: ltr; 
        text-align: left;
        unicode-bidi: bidi-override;
    }
    

    HTML

    <div>hello</div>
    <div>ظ</div>