JavaScript caret position - javascript

I'm developing a mobile banking application and I'm interested in formatting the currency amount inputs in real time.
I've already tested autoNumeric plugin and jQuery Format Currency Plugin but both have cursor position issues on Android 2.* browsers.
Does anyone have a JavaScript solution compatible with this browsers?

I don't know about autoNumeric, but http://code.google.com/p/jquery-formatcurrency/ looks pretty good. The jsFiddle example you posted doesn't place the caret correctly on my desktop browser, but this does, and on my (Jellybean) Android phone as well. (On Gingerbread, the blinking cursor bar may jump to the end of the line, but you will still be editing where it last was.) Try their demo: http://www.bendewey.com/code/formatcurrency/demo/format_as_you_type.html

I usually use accounting.js
You can download it from http://openexchangerates.github.io/accounting.js/#download
It's quite easy to use. You can see how it works from that same download page.
I created a couple javascript functions which i use to do the cursor management:
function formatMoney(myField){
if(myField.selectionStart || myField.selectionStart == '0'){
var len = myField.value.length;
var caretPos = doGetCaretPosition(myField);
myField.value = accounting.formatMoney(myField.value);
var newlen = myField.value.length;
setCaretPosition(myField, newlen != len ? (newlen > len ? caretPos + 1 : caretPos - 1) : caretPos);
}
}
function doGetCaretPosition (ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(elem, caretPos) {
elem.value = elem.value;
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
You can use the functions with the text field as:
<input id="myField" type="text" onkeyup="formatMoney(this);" onChange="formatMoney(this);" onBlur="formatMoney(this);" />
The getting and the setting caret position functions were gotten from here: Set keyboard caret position in html textbox
I tested it on Android 2.1 emulator. Though the emulator was slow but it seemed to be working. You can find the screenshot here: https://www.dropbox.com/s/9ximuwh64kadiea/shot.JPG?dl=0

Here's an open source, well contributed, well commited library : https://github.com/plentz/jquery-maskmoney
Seems to answers your need, doesn't it ?
Havent't tested it under Android though.

It seems this jQuery plugin - NumBox - aims to provide solution to your problem.

Related

Safari does not add a break when hitting enter

I want a user to be able to type in a content editable div, hit enter (or come to the end of the line) and have their text collected into a variable and have their cursor put on a new line, standard for any text editor. I have this event listner that checks for those conditions:
writerId.addEventListener('keydown', function(event){
if(event.key === "Enter" || document.getElementById("writer").offsetWidth >= "570") {
if(initialState === true) {
writtingContent = writerId.innerHTML;
blurId.innerHTML = writtingContent ;
writerId.innerHTML = "";
initialState = false;
} else {
writtingContent = writtingContent + writerId.innerHTML;
blurId.innerHTML = writtingContent ;
writerId.innerHTML = "";
}
}
});
The new line works in Chrome, FireFox but not Safari.
Initially I added this as a workaround for Safari:
if(navigator.userAgent.indexOf("Safari") != -1) {
writtingContent = writtingContent + "</br>";
console.log(navigator.userAgent);
}
But it broke things in other browsers (specifically Opera) and I've read that navigator.userAgent is not the best way to go about browser specific issues anyway.
I've seen some workarounds with feature detection but I'm not sure if that's necessary; I'd love if there was an easier way; something, perhaps, I've overlooked.

Cursor position/index on textarea onClick event in IE11

Scenario : User makes onClick on a textarea(somewhere between the content without selecting any character just a click). Using javascript need to find the position of the cursor.
We had following script :
comp.focus();
var range = document.selection.createRange();
range.text='|';
var oldval = comp.value;
var pos= oldval.index('|');
Code was running with IE <11. With IE 11 ''dcoument.selection' was undefined. Then document says with IE11 "document.selection" should be "document.getSelection". Hence tried the following :
comp.focus();
var range = document.getSelection().createRange();
WIth ver11 , "document.getSelection().createRange()" says errors : Object doesnt support the propery or mehtod 'createRange()'.
Then tried to get object of 'var sel = document.getSelection()'. When i try to print as alert 'sel' , it says 'cannot get property toString on undefiend or null references'
1. With older version document.selection.createRange worked well even if there isnt any character seelcted/highlighted. But with IE11 its not as such.
2. Please let me know how to createRange evne if there isnt any selected characters.
Need solution/suggestion to proceed.......
I use this function to get cursor position:
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
The following code returns cursor position:
comp.getCursorPosition();
works fine with IE11

first line problem in nicedit ?

Hello i have small problem with nicedit editor
the problem is
the first line is can not be affected !
example :
i writed ( asdad ) in the first line of the textarea box
i marked it and clicked on ( center align )
it's should go to the center of the box
see this picture
this problem is only in first line ..
others is work fine
The problem is only in firefox !
i am using firefox 3..... and i see this problem !
my code is
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
<textarea cols=40 rows=10></textarea>
Thank you !
I also had that problem. And we are not alone:) It is nicEditor's bug http://nicedit.com/forums/viewtopic.php?f=4&t=364&p=848&#p848. And looks like it isn't fixed yet.
I've solved this bug by using TinyMCE-editor :) And if you are not tied with nicEditor I would suggest to look on TinyMCE.
I hope it will be helpfull.
I have developed a solution for this.
The problem is the first line that is not in a div.
This will fix it
$(document).ready(function () {
$('.nicEdit-main').bind('DOMSubtreeModified',function(){
nicEditFirstLinePatch();
});
});
and
function nicEditFirstLinePatch(){
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
textNode=$('.nicEdit-main').contents().filter(function(){
return this.nodeType == 3;
})[0];
$('.nicEdit-main').attr('id','toHandle');
if(textNode){
var newNode = document.createElement('div');
var newNodeContent = document.createTextNode(textNode.nodeValue);
newNode.appendChild(newNodeContent);
var parentNode=document.getElementById('toHandle');
parentNode.replaceChild(newNode,textNode);
var range = document.createRange();
range.setStart(newNode,0);
}
if(document.getElementById('toHandle').children.length==1){
placeCaretAtEnd(document.getElementById("toHandle"));
}
}
It works fine on Chrome 55.0.2883.87. I think it's crossbrowser but I'm not sure. however it is a good start :)

Focus textarea with caret after text in Android browser

I am currently writing a simple webapp to view tweets in the Android browser.
I am using this code to focus the caret after the current text:
var oldContent = document.tweetBox.tweet.value;
document.tweetBox.tweet.value = '';
document.tweetBox.tweet.focus();
document.tweetBox.tweet.value = oldContent + to;
This code works flawlessly in Chrome, Fluid, Opera, Firefox en Safari.
The weirdest part is that the cursor starts blinking AFTER the 'to' text if I use my hardware keyboard but the text that I enter starts where I was typing before the JS above was executed.
If I use the soft keyboard the text entering starts at the start of the textarea.
p.s The javascript is part of a suggestion for followers, so if you start typing #gn it will suggest #gnur_nl in a seperate div and when you press enter this entry is chosen.
Update: This behaviour seems to be the result of a browser bug, a bug report has been filed.
Sounds like a browser bug. Try setting the caret position manually:
var textArea = document.tweetBox.tweet, oldContent = textArea.value;
textArea.value = oldContent + to;
textArea.focus();
textArea.selectionStart = textArea.selectionEnd = textArea.value.length;
setCaret = function(obj,pos) {
// IE Support
if (document.selection) {
// Set focus on the element
obj.focus ();
// Create empty selection range
var oSel = document.selection.createRange ();
// Move selection start and end to 0 position
oSel.moveStart ('character', -obj.value.length);
// Move selection start and end to desired position
oSel.moveStart ('character', pos);
}
//standard browsers
else if (obj.selectionStart || obj.selectionStart == '0') {
obj.selectionStart = pos;
obj.selectionEnd = pos;
obj.focus ();
}
};
and setting to the right positions
setCaret(document.getElementById("area"),document.getElementById("area").value.length);

How do i set the cursor in a html editor using IE (7-8)

Actually i am trying to set the cursor to a specific node inside a html editor (which uses a contenteditable iframe). For example i have several paragraphs and want the cursor to move to the start of the previous paragraph.
Unfortunatly, the Internet Explorers range object does not support setStartBefore and setStartAfter. The ierange project is not an option - the solution i am looking for needs to work with IE out of the box.
How do i set the cursor in IE?
In Firefox the solution is straight forward:
// sets the cursor position (start defines, if cursor is needed at the start or end of the node)
function setCursor(editor, node, start){
var tn = editor.getDoc().createTextNode("."); // gets the editors document
if (start){
node.insertBefore(tn, node.firstChild);
}
else node.appendChild(tn);
rng = editor.selection.getRng(); // gets the browsers range object for the users selection
rng.selectNode(tn);
rng.setStartBefore(tn);
rng.setStartAfter(tn);
ed.selection.setRng(rng);
node.removeChild(tn); // removes the caret node - curser is placed now
}
You could use my Rangy project for this. The code would then be the same in all browsers:
function setCursor(element, start) {
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
rangy.init();
var range = rangy.createRange(doc);
range.selectNodeContents(element);
range.collapse(start);
rangy.getSelection(win).setSingleRange(range);
}
Alternatively, this particular case isn't too tricky without a library:
function setCursor(element, start) {
var doc = element.ownerDocument || element.document;
if (typeof doc.createRange != "undefined") {
var range = doc.createRange();
range.selectNodeContents(element);
range.collapse(start);
var win = doc.defaultView || doc.parentWindow;
var sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof doc.body.createTextRange != "undefined") {
var textRange = doc.body.createTextRange();
if (start) {
textRange.moveToElementText(element);
textRange.collapse(start);
} else {
var markerEl = doc.createElement("span");
markerEl.innerHTML = "\u00A0";
element.appendChild(markerEl);
textRange.moveToElementText(markerEl);
element.removeChild(markerEl);
}
textRange.select();
}
}
Working with the Cursor Position
(This solution works for me in IE, Firefox and Opera)

Categories

Resources