Created
January 25, 2012 08:37
-
-
Save milani/1675462 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function formatTag(tag){ | |
var elements = $('content').getElementsBySelector(tag); | |
elements.forEach(function(P,index){ | |
// calculate frequency of characters for the first few characters ( 30 ) | |
var charCode, | |
arabicFreq = 0, | |
englishFreq = 0, | |
length = 30, | |
parentDir = $(P).getStyle('direction'), | |
text = P.innerText; | |
for(var i = 0; i < length; i++){ | |
charCode = text.charCodeAt(i); | |
if(1536 < charCode && charCode < 1791){ | |
// Arabic Script | |
arabicFreq++; | |
}else if(65 < charCode && charCode < 122){ | |
// English Script | |
englishFreq++; | |
}else{ | |
// Special chars | |
} | |
} | |
if(arabicFreq < englishFreq && parentDir != 'ltr'){ | |
// English Script in rtl container | |
$(P).setStyle({'direction':'ltr'}); | |
}else if(arabicFreq > englishFreq && parentDir != 'rtl'){ | |
// Arabic Script in ltr container | |
$(P).setStyle({'direction':'rtl'}); | |
} | |
}); | |
} | |
function align(){ | |
var tags = ['p','ul','li']; | |
tags.forEach(function(tag){ | |
formatTag(tag); | |
}); | |
var textareas = $$('textarea'); | |
textareas.forEach(function(textarea,index){ | |
var charCode,arabicFreq = 0,englishFreq = 0; | |
Event.observe(textarea,'keyup',function(e){ | |
var sentence = $(this).value; | |
if(sentence.length > 60) return; | |
arabicFreq = 0; | |
englishFreq = 0; | |
for(var i = 0; i < sentence.length; i++){ | |
charCode = sentence.charCodeAt(i); | |
if(1536 < charCode && charCode < 1791){ | |
// Arabic Script | |
arabicFreq++; | |
}else if(65 < charCode && charCode < 122){ | |
// English Script | |
englishFreq++; | |
} | |
} | |
// where is the first character of this paragraph? | |
if(arabicFreq < englishFreq){ | |
$(this).setStyle({direction:'ltr'}); | |
}else{ | |
$(this).setStyle({direction:'rtl'}); | |
} | |
}); | |
}); | |
} | |
Event.observe(window, 'load', align); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment