How can I automatically set text direction based on input text language? - javascript

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

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

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';
}
});
});

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

There's also Twitter's library, which may help:
https://github.com/twitter/RTLtextarea

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')

list the right to left languages typical characters
detect them on the fly (usual js events)
change css classes accordingly
Or follow this link:
http://www.i18nguy.com/temp/rtl.html

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

Related

Regex to extract particular attribute and innerHTML of a div inside contentEditable

Background
I am creating a #Name Tagging system for my webpage. and I've succeeded in finding names on keystroke and replace the content with equivalent div class='tag' data-id='User-id'>Name</div>(at least for displaying). Now before submitting those contents from contentEditable div. I modify them in a textarea (which is usually hidden).
Working
As soon as .keyup event occurs on contentEditable all the contents of contentEditable are processed by function MakeItForWeb(contentEditable). Which then Manipulates the contents of textarea which will be processed by server side php script. that php script will strip all the tags and then store data in DB. so before submitting I try to replace all the .tag div with following format of data:
#["id":"User-id","Tag":"User-Name"];
In <textarea>, I have created a regular expression in javascript to achieve the task. and it is working fine, when there is single .tag in single line, You can see it Here.
Problem
When More than 1 .tag occurs in a single line then My regex fails to recognize all of them correctly, and recognize only last of them. And thus whole tagging system crashes, You can see it Here. May be My approach is wrong. Can Experts here help me out please? any suggestion is welcome.
My Efforts(Code)
JavaScript + JQuery:
$(document).ready(function(){
$("body").attr("spellcheck","false");
$("#tarea").keyup(function(e){ // Process KeyUp Event
/* Code to find Names on #N..and create a tag is omitted purposefully as it is working fine */
// Make each tag Un-editable, So that User cant change it
$(".tag").each(function(){
$(this).attr("contentEditable","false");
});
//Manipulate the textarea with equivalent value
MakeItForWeb(this);
}).focus(function(){
//Manipulate the textarea with equivalent value from contentEditable
MakeItForWeb(this);
});
$("#tarea").trigger("keyup"); // Trigger keyUp event as soon as DOM ready.
});
function MakeItForWeb(x){
var htm=$(x).html(); // Contents of contentEditable
htm=htm.split("<br>").join("\n"); // Replace <br> with \n character
htm=htm.split(" ").join(" ");
htm=htm.trim(); // Trim contents
/* Here is My regex which does the mentioned task */
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"#['id':'$2','tag':'$4'];");
document.getElementById("opc").value=htm; // <textarea> = ContentEditable processed.
}
Note the Line:
htm=htm.replace(/<div(.*) data-id=\"(.*)\" (.*)>(.*)<\/div>/g,"#['id':'$2','tag':'$4'];");
// This is My Regex.
// where var htm=contentEditable.innerHTML;
HTML:
<div id="tarea" contentEditable="true" class="tarea" autocorrect="false" spellCheck="off">
Hello Says! <div class="tag" data-id="1005">Vedant Terkar</div> , <br />To all <div class="tag" data-id="1006">SO Users</div> :-).
</div>
<!-- This textarea is Usually Hidden -->
<textarea id="opc" rows="5" cols="97">
</textarea>
css is irrelevant to problem, so not posting it.
Hope experts here will help me out. Thanks in advance :-) !
Regex:
<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*?\/>([^<]*)<div\b.*?\bdata-id=\"([^"]*)\">([^<]*).*
Replacement string:
#['id':'$1','tag':'$2']; , $3#['id':'$4','tag':'$5'];
DEMO
Get the matched group from index 1 and 2. I used Lazy way.
<div class="tag" data-id=\"([^\"]*?)\">([^<>]*?)<\/div>
here is online DEMO
Try this one to get the "Hello Says!" and "To all" as well in 3 catapulting groups.
>\s*([^<>]*)<div class="tag" data-id=\"([^\"]*?)\">([^<>]*?)<\/div>
here is online DEMO

javascript/css: change display property

I want to change display without documentGetElementById if possible but the following is not working.
html
Instructions<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
javascript:
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
divname.style.display="block";
}
Can anyone tell me what I am doing wrong?
Thank you.
I can't get why you do not want to use getElementById, but...
If you have elements in order like this
Instructions
<div id="showfaq1" style="display:none;">Open Box. Remove device. </div>
Instructions
<div id="showfaq2" style="display:none;">Open Box. Remove device. </div>
...
Instructions
<div id="showfaqN" style="display:none;">Open Box. Remove device. </div>
You may use
Instructions
function toggleFaq(obj) {
obj.nextElementSibling.style.display = 'block';
}
In your code divname is a variable containing a string "showfaq1", which doesn't have style property.
To change the style of an element you need a reference to that element which you can obtain using document.getElementById(divname):
function toggleFaq(faqid) {
//alert(faqid);
var divname = "showfaq"+faqid;
//alert(divname);
document.getElementById(divname).style.display="block";
}
If you have an allergy to document.getElementById, you may use document.querySelector('[id="' + divname +'"]');, but its support is not as good as the former, and it's slower.
Posting a separate answer as it has no impact on my previous one. But you could make the base mechanism without JS at all, then use one of the JS-based solutions to fix it in broken browsers if needed:
HTML
Instructions
<div id="showfaq1">Open Box. Remove device. </div>
CSS
a + div { display:none; }
a:focus + div, a + div:target { display:block; }
DEMO

How to identify if user is typing in RTL or LTR language?

I want imitate google's input,
It automatically change input's typing direction based on the language you're typing in.
How can I identify if user is typing in RTL or LTR language?
It must work cross-browser.
You should use the attribute dir="auto"
e.g.
<html dir="auto">
This way the browser will look at the first strongly typed character and adjust the text automatically.
For reference, here is the W3C documentation on this: http://www.w3.org/International/tutorials/new-bidi-xhtml/qa-html-dir
If you want to mimic Google's directionality recognition algorithm, you will need to listen to input change, recognize whether the character inserted was RTL or LTR (or neutral) and change the textbox's dir="" attribute accordingly.
Google's algorithm, for the most part, seems to calculate the majority of strong characters in the string and decide the directionality from that. If you type RTL it will switch the context to RTL, and if you then switch to LTR for the same paragraph, it may switch the context again to LTR if those characters outnumber the RTL ones.
For comparison, Facebook uses a direction algorithm as well, but it is slightly different - it seems to use the first strong character to decide the direction of the paragraph rather than the overall number.
(For the record, Google also seems to have several algorithms for this; Gmail behaves slightly differently than Google Hangouts which is different than how the input in Google search is aligning itself. In these things, there are mostly no "right" or "wrong" answers but rather what fits your use case)
Whichever method you choose to implement, you first need to identify what the user is typing. There are several ways to do this, but I would recommend the following:
Read a little about Unicode BiDirectional Algorithm (especially about "strong" type characters) http://unicode.org/reports/tr9/
Find a good way to identify strong characters in your context. An example of a regex to do that can be found in MediaWiki's Language file (where group 1 is LTR and group 2 is RTL): https://github.com/wikimedia/mediawiki/blob/6f19bac69546b8a5cc06f91a81e364bf905dee7f/languages/Language.php#L174
You can create a JavaScript method that listens to the user's input, uses the regex above to identify which strong character is used (either by first character or by counting them all, whichever works best for your use and scale) -- and change the textbox's dir="" attribute accordingly.
Make sure you later display the submitted text with the correct alignment later, so you may have to either use something to store the alignment you picked or to re-recognize whenever you render it. Either way, don't forget that the display needs the same dir="" attribute as well.
Too late but maybe it can help someone one day.
This function will add direction attribute to the input field based on the first inputed character, and when user clears input text the function will detect the new language of text again.
$.fn.set_input_direction = function()
{
$(this).off('keypress').on('keypress',function(e){
_this = $(this);
setTimeout(function()
{
if(_this.val().length > 1){
return;
} else {
var rtl_regex = /[\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC]/;
var is_rtl = rtl_regex.test(String.fromCharCode(e.which));
var direction = is_rtl ? 'rtl' : 'ltr';
_this.css({'direction' : direction});
}
});
});
};
To use it:
$('input').set_input_direction();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script>
function checkRTL(s) {
var ltrChars = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + '\u2C00-\uFB1C\uFDFE-\uFE6F\uFEFD-\uFFFF',
rtlChars = '\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC',
rtlDirCheck = new RegExp('^[^' + ltrChars + ']*[' + rtlChars + ']');
return rtlDirCheck.test(s);
};
// BIND KEYPRESS
var input = $('input').on('keypress', keypress)[0];
function keypress(e) {
// need to wait for the character
setTimeout(function () {
var isRTL = checkRTL(String.fromCharCode(e.charCode)),
dir = isRTL ? 'RTL' : 'LTR';
input.style.direction = dir;
}, 0);
}
</script>
</head>
</body>
<h1>Auto Direction
<sup>(RTL | LTR)</sup>
</h1>
<input type="text" onkeypress="keypress()" placeholder="Type something…" />
</body>
</html>

How to make prices in different color

I want to display prices followed by a $ sign in a different color in the heading. I don't want to display all numbers in different color - just where $ sign appears and the digits after that. There could be up to two numbers after the decimal point in some cases e.g. where price is $12.50
I have access to both HTML and CSS on the server.
Please see below code that is used to display heading. Please let me know how I change this code.
{$title_short}
Thanks for your help in advance in solving this.
Example:
If you have access to the HTML, you can simply wrap all the prices in a span tag and assign some class to them. Then just use CSS to set the color:
<span class="price">$12.34</span>
Why not just add a span like:
css:
span.money{
color: red;
}
html:
$<span class="money">12.50</span>
If I understand correctly, this should do the trick if you use jQuery
$('element:contains("$")').css('color', 'whatever color you'd like');
Example
$('table th:contains("$")').css('color', 'yellow');
Assuming , you the values are in a tag (or any selectable node) , you can replace them back with a regex . Something like
$('p:contains("$")').html(function(i,html){
return html.replace(/(\$\d+(\.\d+)?)/g,function($1){
return '<em class="money">'+$1+'</em>';
});
});
Here's a quick demo .
http://jsfiddle.net/ngcBg/

Fix a character to text input box using javascript/jquery

I am looking for a way to 'fix' a dollar symbol $ to a text input box eg <input type="text" value="$" /> but make it not possible for the default value to be removed, so that whatever the user inputs, there is always a $ symbol 'prepending' input.
Cheers
There is the possibility of a background-image but it's difficult to maintain, and doesn't react to font size changes, which makes it the less optimal choice IMO.
A better way in my opionion would be:
Put a <span>$</span> next to the input (before it, actually).
give it position: relative; left: 20px.
The $ sign then moves into the input field.
Then, give the input field padding-left: 24px.
Voilá! The $ sign is in the input field, does not obscure anything, and cannot be removed.
Expanding on Pekka's answer, I used this on my page, but I automated it a little bit with jQuery. So for this example, all of the input fields that I want to put a $ symbol in, I give them a class of "cost".
CSS:
<style type="text/css" media="screen">
.cost{
position: relative;
left: 20px;
}
input.cost{
padding-left: 24px;
}
</style>
jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#lcce form input.cost").wrap('<div class="cost">');
$("#lcce form input.cost").before('<span class="cost"></span>');
});
</script/>
This will place the span with a class of "cost" right before your input, and also wrap a div around both the input, and the span, so they are ensured to be on the same line.
If you don't have jQuery, you can get it from: jQuery.com
Now I've got a quick question - I noticed that with this styling, in IE6,7, and 8, the $ symbol is not lined up correctly. Does anybody out there have a fix for this?
Thank you!
Is this as a visual effect only? If yes you could apply that with CSS as a background image on the input.
Afterwards, on the server, you can do whatever you want with the value (e.g prepend it with $).
I too have been looking at different solutions for this. Using css to indent the text with padding and putting a background image in that position is your best bet.
I did it like this:
$('#price').keypress(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if ($(this).val().indexOf('$') === -1){
document.getElementById("price").value = "$" + $(this).val();
} else {
document.getElementById("price").value = $(this).val();
}
});
with <input type="text" id="price">.
User can remove the dollar sign manually though if he/she wants to.

Categories

Resources