Insert text at caret position IE 8 - javascript

I want to be able to enter some text at the caret position. Currently I can insert text at the end or start of the textbox OR replace the whole textbox content with the new text. How can I get the new text to insert into the textbox at the caret position?
What I want:
i.e textbox contatins "12,3" with caret being where the coma is. After function call it ends up like so: "12new text3"
Current code:
var sel = document.getElementById("txtbox");
var text = "new text";
//ie 8
if (document.selection) {
var range = document.selection.createRange();
sel.focus();
range = sel.createTextRange();
range.collapse(false);
range.text = text;
range.select();
}

I've not IE8 to test, but try this:
if (document.selection) {
var range = document.selection.createRange();
range.text = text;
range.select();
}
In your code you've defined range twice, and then collapsed the range (containing all the text in a textbox) to the end of the text.

Related

Move cursor position in textarea to start position after setting value

HTML:
<textarea id="text-box" size="20"></textarea>
<button onclick="selectText()">Get Content</button>
JavaScript:
function selectText() {
var txtArea = document.getElementById('text-box');
txtArea.value = "Some Text";
txtArea.focus();
console.log(txtArea.value.length)
var sel = window.getSelection();
var range = sel.getRangeAt(0);
console.log('range.collapsed',range.collapsed)
range.collapse(true);
}
The above code indicates that the range is already collapsed, and the newly set content isn't selected. The cursor is at the end of the content. I want the cursor to be set to the beginning of the content. If I set the selection to the entire content, and then try to collapse it, the following code doesn't work.
Tried:
function selectText() {
var txtArea = document.getElementById('text-box');
txtArea.value = "Some Text";
txtArea.focus();
console.log(txtArea.textContent.length)
txtArea.setSelectionRange(0, txtArea.value.length);
var sel = window.getSelection();
console.log(sel.rangeCount)
sel.collapseToStart();//Doesn't work
//Also tried the following
//var range = sel.getRangeAt(0);
//range.collapse(true);
}
I try the code sel.collapseToStart() and its work fine. So maybe its a compatibility issues. What browser do you use?
https://codepen.io/gwtjs/pen/qzrJbp

selection.toString() returns empty string despite of a selected range

I am trying to select an element's text on click using the following code:
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
Although the text is getting highlighted, empty string is copied to the clipboard on using Ctrl + C. Checking for selection.toString() returns an empty string too. Any idea why can this be happening?
Hm, I took a look at your code and tried:
var selection = window.getSelection();
var selectionText = selection.anchorNode.textContent
and I got the selected text content.
EDIT: it appears this was wrapped in a click function...one second.
$('<your selector goes here>').click(function(e) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(e.target);
selection.removeAllRanges();
selection.addRange(range);
console.dir(selection.anchorNode.textContent);
//text content should display...
//now that the content is highlighted, you can copy it
document.execCommand('copy');
})

Prevent loss of highlight when clicking on other element

I'm working on a blog where I want a section to add a post. I'm imagining it very similar to the StackExchange editor I'm using right now to write this post.
I've managed to work with the textarea to get things like current caret position, insert at position, etc.
The problem I'm running into now is not losing the highlighted text in the textarea when the user clicks on another element, ie: the bold tool.
By default (at least in Chrome) when you highlight text in a textarea and then click elsewhere on the page, the textarea loses focus and the highlighted text with it.
When the textarea loses focus it will by default lose any previous selection, so at the onblur event you can save the current selection using the following function:
function getSelectedText() {
var txtarea = document.getElementById(textBoxScript);
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
var sel = txtarea.value.substring(start, finish);
return sel;
}
And to set it back on focus event you can use the following function:
function selectText(startPos, endPos, tarea) {
// Chrome / Firefox
if (typeof (tarea.selectionStart) != "undefined") {
tarea.focus();
tarea.selectionStart = startPos;
tarea.selectionEnd = endPos;
return true;
}
// IE
if (document.selection && document.selection.createRange) {
tarea.focus();
tarea.select();
var range = document.selection.createRange();
range.collapse(true);
range.moveEnd("character", endPos);
range.moveStart("character", startPos);
range.select();
return true;
}
}

js/jquery: contenteditable, insert text and move cursor to end

I need to insert text into a contenteditable div and then have the cursor be at the end of the inserted text.
I got the solution below from here Insert text at cursor in a content editable div.
That works great if the text is added to am empty div. But it does not work if the user has already typed in text. Or, if the function is used to insert text, the user then places the cursor somewhere inside the newly inside text, and the function is then called again. Then the cursor is left at the beginning of the inserted text.
EDIT: The code below works in IE, properly setting the cursor, but has the problem in Chrome.
function insertTextAtCursor(text) {
var sel, range, html;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode( document.createTextNode(text) );
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}
Alright, once I realized it was a Chrome/IE thing I managed to find the answer tucked away inside one of the comments to the answer that I first found.
function insertTextAtCursor(text) {
var sel, range, html;
sel = window.getSelection();
range = sel.getRangeAt(0);
range.deleteContents();
var textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
sel.removeAllRanges();
sel.addRange(range);
}

How to remove all nodes from selected ranges

For example, I have such text:
Some test <span> in span1</span> sss <span>in span2</span> end of text.
when I select " test in span1 sss in spa" I want to just delete parent spans of selected ranges and create new range
that will contain my selected text.
Some<span> test in span1 sss in spa</span>n2 end of text.
I'm using window.getSelection(),range,nodes
Please help!
You can do this with the deleteContents(), toString() and insertNode() methods of a range obtained from the selection.
The following will work in all major browsers except IE <= 8. You'll need a different approach for those browsers, which I can outline if you need it.
Demo: http://jsfiddle.net/HUm2K/
Code:
var sel = window.getSelection();
if (sel.rangeCount > 0) {
var range = sel.getRangeAt(0);
var newSpan = document.createElement("span");
var selectedTextNode = document.createTextNode( range.toString() );
newSpan.appendChild(selectedTextNode);
range.deleteContents();
range.insertNode(newSpan);
range.selectNode(newSpan);
sel.removeAllRanges();
sel.addRange(range);
}

Categories