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
Related
I have tried anything to get the selected text for a context menu, but it is not working in IE11.
For context menu adding I have added some code in registry, and a htm file with a Javascript.
First I have tried this:
var parentwin = external.menuArguments;
var doc = parentwin.document;
var sel = doc.selection;
var rng = sel.createRange();
var selectedtext = new String(rng.text);
then I have read in IE11 documentation, the document.selection has been repalced in the API with window.getSelection();
So I have tried any variant, window.getSelection... nothing works...
Any idea how I can access the selected text?
And I have searching also how I can copy to the clipboard.. in chrome I have used this script:
function copyToClipboard(text){
var copyDiv = document.createElement('div');
copyDiv.contentEditable = true;
document.body.appendChild(copyDiv);
copyDiv.innerHTML = text;
copyDiv.unselectable = "off";
copyDiv.focus();
document.execCommand('SelectAll');
document.execCommand("Copy", false, null);
document.body.removeChild(copyDiv);
}
Finally I have found the solution: (tested in IE11)
var parentwin = external.menuArguments
var selectedText = getSel();
function getSel(){
var w=window,d=parentwin.document,gS='getSelection';
return (''+(w[gS]?w[gS]():d[gS]?d[gS]():d.selection.createRange().text)).replace(/(^\s+|\s+$)/g,'');
}
parentwin.console.log("the selected text is:"+sel);
copyToClipboard(selectedText);
function copyToClipboard(s) { //only works in IE :(
if (window.clipboardData && clipboardData.setData) {
clipboardData.setData('text', s);
}
}
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.
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);
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)
I'm building a wysiwyg-editor with an editable iframe using document.execCommand(). Now i need to use the "insertHTML" command which works perfectly in Chrome and Firefox but of course it doesn't work in Internet Explorer:
function run() {
document.getElementById("target").focus();
document.execCommand("insertHTML", false, "<b>ins</b>");
}
<div contenteditable id="target">contenteditable</div>
<button onclick="run()">contenteditable.focus() + document.execCommand("insertHTML", false, "<b>ins</b>")</button>
What is the standard solution to this problem? It's okay if it only works in IE8 but IE7-support would be nice too.
In IE <= 10 you can use the pasteHTML method of the TextRange representing the selection:
var doc = document.getElementById("your_iframe").contentWindow.document;
if (doc.selection && doc.selection.createRange) {
var range = doc.selection.createRange();
if (range.pasteHTML) {
range.pasteHTML("<b>Some bold text</b>");
}
}
UPDATE
In IE 11, document.selection is gone and insertHTML is still not supported, so you'll need something like the following:
https://stackoverflow.com/a/6691294/96100
In case you haven't found anything yet,
I had a button that would add html into an iframe, and was causing an error in IE8 when I clicked the button and no text was selected (i.e. when I had the blinking caret). It turned out that the button itself was getting selected (despite having unselectable="on"), and causing javascript to throw up the error. When I changed the button to a div (with unselectable on) it worked fine, in IE8 and FF.
Hope this helps.
I know this is extremely old, but since IE is still a problem, here is a better way which does not even use execCommand.
This is missing some checks, like ensuring you're in the right container to be adding an image.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var frag = document.createDocumentFragment();
var img = document.createElement("img");
// add image properties here
frag.appendChild(img);
range.insertNode(frag);
var doc = document.getElementById("your_iframe").contentWindow.document;
// IE <= 10
if (document.selection){
var range = doc.selection.createRange();
range.pasteHTML("<b>Some bold text</b>");
// IE 11 && Firefox, Opera .....
}else if(document.getSelection){
var range = doc.getSelection().getRangeAt(0);
var nnode = doc.createElement("b");
range.surroundContents(nnode);
nnode.innerHTML = "Some bold text";
};