Reputation: 2282
I want to make my site supporting both LTR and RTL languages.
What I want is, if text loaded in some element is RTL then switch direction to RTL. Also for inputs, when user type text, it should trigger if it's RTL and change direction to RTL.
Like Facebook is doing it for example. If you type some Arabic text in search it will automatically switch direction to RTL
Didn't found any practice tutorial by googling, any script or so.
I only found attribute dir="auto"
which automatically triggers correct direction but looks like this it is not supported with older Browsers.
Any advice, tutorial, script how to do this would help.
Upvotes: 3
Views: 534
Reputation: 231
If you only want to support switching the textbox context from LTR to RTL when the user types, then you will have to listen to the input events (input, keypress, keydown, etc, whichever works best for your case) and let the code decide whether the textbox is LTR aligned or RTL aligned.
You should note, though, that the algorithm for this is not all that straight forward, and that different products work differently. A few examples -
There is no right or wrong here, there's only preference and what works best as your algorithm.
You can read about "strong characters" in the Unicode Bidirectional Algorithm here: http://unicode.org/reports/tr9/
You can see an example of how to recognize the first "strong character" in a string for embedding purposes in MediaWiki's language file, with the regex that tests directionality (group 1 is LTR and group 2 RTL) You can use these to create a JavaScript method that sets your textarea's dir="" attribute based on either the first strong character or the majority of characters, as you see fit: https://github.com/wikimedia/mediawiki/blob/6f19bac69546b8a5cc06f91a81e364bf905dee7f/languages/Language.php#L174
As a side note, I will just point out that supporting RTL/LTR online is not just about typing and textboxes. Changing between LTR and RTL contexts also involves UI adjustments, like mirroring the alignment of the content and/or the positions of things like menus and the logo.
This is relevant if you want to allow your page to be translated to an RTL language, which means you will need to also mirror the layout. If your only goal is to switch contexts in the textbox, you shouldn't worry about this, but if you want to make sure the site allows for translation, you need to consider methods of mirroring your UI and your entire interface.
Upvotes: 1