18

In Google plus (and a lot of other places), when I want to post something, when I type it in Persian, which is a right-to-left language, text direction is automatically set to rtl and text-alignment:right, and when I start to type in English it changes automatically to ltr and text-alignment:left. How can I have such functionality? Is this anything with HTML5 or Javascript? What clues should I follow?

Thanks in advance

Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119
Mostafa Shahverdy
  • 2,687
  • 2
  • 30
  • 51

7 Answers7

21

Add dir=auto to your input elements:

Use dir="auto" on forms and inserted text in order to automatically detect the direction of content supplied at run-time.

https://www.w3.org/International/questions/qa-html-dir#quickanswer

Amir Nissim
  • 3,173
  • 2
  • 24
  • 19
9

I wrote a JQuery code to do this. Just add class "checkRTL" to the element you want to set its direction.

var rtlChar = /[\u0590-\u083F]|[\u08A0-\u08FF]|[\uFB1D-\uFDFF]|[\uFE70-\uFEFF]/mg;
$(document).ready(function(){
    $('.checkRTL').keyup(function(){
        var isRTL = this.value.match(rtlChar);
        if(isRTL !== null) {
            this.style.direction = 'rtl';
         }
         else {
            this.style.direction = 'ltr';
         }
    });
});
Sherif Khaled
  • 99
  • 1
  • 2
9

I was having issue with dir=auto sometimes not working.

After digging CSS I found

#container > * {
    text-align: start;
    unicode-bidi: plaintext;
}

More flexible and universal

realsarm
  • 583
  • 6
  • 11
4

There's also Twitter's library, which may help:

https://github.com/twitter/RTLtextarea

Amir E. Aharoni
  • 1,308
  • 2
  • 13
  • 25
4

Add dir="auto" to your element and then use window.getComputedStyle(element).getPropertyValue('direction')

Example:

<div id="foo" dir="auto">نے والے ہیں۔<div>

// returns rtl
window.getComputedStyle(document.getElementById('foo')).getPropertyValue('direction')
Fawaz Ahmed
  • 1,082
  • 2
  • 14
  • 18
2
  1. list the right to left languages typical characters
  2. detect them on the fly (usual js events)
  3. change css classes accordingly

Or follow this link:

http://www.i18nguy.com/temp/rtl.html

Sebas
  • 21,192
  • 9
  • 55
  • 109
  • 1
    Well, As you suggested, I detect characters using RegExp like `ltrChars : 'A-Za-z\u00C0-\u00D6 .....`, and change CSS classes whenever they are needed. – Mostafa Shahverdy Mar 16 '13 at 16:30
2

window.getComputedStyle(document.getElementById('foo')).getPropertyValue('direction')
<div class="" id="foo">

<div class="English">this is test message</div>
<div class="Persian">این یک پیام تستی است</div>
<div class="Persian-English">test برای حالت فارسی</div>

</div>

In Persian, if first sentence starts with an English word like last div, the whole text is placed in LTR mode

roXen
  • 27
  • 5