Reputation: 643
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?
Upvotes: 5
Views: 7925
Reputation: 1149
function isUnicode(str) {
return (str.charCodeAt(str.length-1) > 255) ? true : false;
}
$('input[type=text]').each(function() {
$(this).keyup(function(e) {
$(this).css('direction',
isUnicode($(this).val()) ? 'rtl' : 'ltr'
);
});
});
Upvotes: 0
Reputation: 13166
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');
}
Upvotes: 4
Reputation: 5136
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');
});
Upvotes: 2
Reputation: 4064
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
Upvotes: 3
Reputation: 4064
What about
jQuery( document ).ready( function(){
var language = navigator.userLanguage || navigator.language;
if( jQuery.inArray( language, ['ar', 'he', 'ur'] ) != -1 )
jQuery( 'input[type="text"], input[type="password"], textarea' ).css( 'direction', 'rtl' );
});
?
edit: fixed little code-bug
Upvotes: 0
Reputation: 6466
Toggle the elements' css with jquery (assuming the relevant inputs/textareas all have the class textdirectionBoxes
):
$('.textdirectionBoxes').css('direction', 'rtl');
and
$('.textdirectionBoxes').css('direction', 'ltr');
Upvotes: 0