Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery to switch between left and right text-alignment, depending on the language

I have input boxes and textareas that need to be toggled between left-alignment and right-alignment (depending on the user's language, the direction would be different). How can I do this with jQuery?

like image 225
Kate Wintz Avatar asked Dec 21 '11 20:12

Kate Wintz


People also ask

How to change LTR to rtl in html?

Add dir="rtl" to the html tag any time the overall document direction is right-to-left (RTL). This sets the default base direction for the whole document. All block elements in the document will inherit this setting unless the direction is explicitly overridden.

How do I move text from left to right in HTML?

The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top.


3 Answers

As I don't know the key code for all Persian letters, I had to do it like this:

var str = $('#item').val();  //this is your text box
var firstChar = str.substr(0,1);
var characters = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
function checkPersian() {
    var result = false;
    for (i = 0 ; i<32 ; i++) {
        if (characters[i] == firstChar) {
            result = true;
        }
    }
    return result;
}
if (checkPersian()) {
    $('#item').css('direction','rtl');
} else {
    $('#item').css('direction','ltr');
}
like image 64
Mohammad Saberi Avatar answered Nov 14 '22 23:11

Mohammad Saberi


Here I have completely overhauled Mohammad's script but it's limited to its purpose: scanning if the first letter the user types in is Persian and changing the inputs direction according.

Here it is: jsfiddle.net/uPH7N/4

like image 42
Matmarbon Avatar answered Nov 14 '22 23:11

Matmarbon


You can use dir="auto" attribute in modern browsers: Live Demo

<input type="text" dir="auto"><br>

Also you can do it by jQuery like this: Live Demo

$('input, textarea').keyup(function() {
    $(this).val().charAt(0).charCodeAt(0) < 200 ? $(this).css('direction','ltr') : $(this).css('direction','rtl');
});
like image 31
Siamak Motlagh Avatar answered Nov 14 '22 22:11

Siamak Motlagh