html - selection range - getting the range + starting node + ending node + distance - javascript

From my previous question for selecting specific html text, I have gone through this link to understand range in html string.
For selecting a specific text on html page. We need to follow this steps.
Assumed HTML:
<h4 id="entry1196"><a
href="http://radar.oreilly.com/archives/2007/03/call_for_a_blog_1.html"
class="external">Call for a Blogger's Code of Conduct</a></h4>
<p>Tim O'Reilly calls for a Blogger Code of Conduct. His proposals are:</p>
<ol>
<li>Take responsibility not just for your own words, but for the
comments you allow on your blog.</li>
<li>Label your tolerance level for abusive comments.</li>
<li>Consider eliminating anonymous comments.</li>
</ol>
java script to make selection by range
var range = document.createRange(); // create range
var startPar = [the p node]; // starting parameter
var endLi = [the second li node]; // ending parameter
range.setStart(startPar,13); // distance from starting parameter.
range.setEnd(endLi,17); // distance from ending parameter
range.select(); // this statement will make selection
I want to do this in invert way. I mean, assume that selection is done by user on browser (safari). My question is that How can we get starting node (as we have 'the p node' here) and ending node (as we have 'the second li node' here) and the range as well (as we have 13,17 here)?
Edit : my efforts (From this question)
var sel = window.getSelection();
if (sel.rangeCount < 1) {
return;
}
var range = sel.getRangeAt(0);
var startNode = range.startContainer, endNode = range.endContainer;
// Split the start and end container text nodes, if necessary
if (endNode.nodeType == 3) {
endNode.splitText(range.endOffset);
range.setEnd(endNode, endNode.length);
}
if (startNode.nodeType == 3) {
startNode = startNode.splitText(range.startOffset);
range.setStart(startNode, 0);
}
But, yet I am confused about getting like, if selected is first paragraph or second or third, or selected is in first heading or second heading or what....

Storing the selected range is simple. The following will return only the first selected range (Firefox at least supports multiple selections):
<script type="text/javascript">
function getSelectionRange() {
var sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection) {
return document.selection.createRange();
}
return null;
}
var range;
</script>
<input type="button" onclick="range = getSelectionRange();"
value="Store selection">
range will have properties startContainer (the node containing the start of the range), startOffset (an offset within the start container node: a character offset in the case of text nodes and child offset in elements), endContainer and endOffset (equivalent behvaiour to the start properties). Range is well documented by its specification and MDC.
In IE, range will contain a TextRange, which works very differently. Rather than nodes and offsets, TextRanges are concerned with characters, words and sentences. Microsoft's site has some documentation: http://msdn.microsoft.com/en-us/library/ms533042%28VS.85%29.aspx, http://msdn.microsoft.com/en-us/library/ms535872%28VS.85%29.aspx.

Related

How to place cursor at end of text in text input element in IE [duplicate]

I need to move caret to end of contenteditable node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable elements.
Geowa4's solution will work for a textarea, but not for a contenteditable element.
This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable.
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
It can be used by code similar to:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
If you don't care about older browsers, this one did the trick for me.
// [optional] make sure focus is on the element
yourContentEditableElement.focus();
// select all the content in the element
document.execCommand('selectAll', false, null);
// collapse selection to the end
document.getSelection().collapseToEnd();
There is also another problem.
The Nico Burns's solution works if the contenteditable div doesn't contain other multilined elements.
For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems.
In order to solve them, I've arranged the following solution, that is an improvement of the Nico's one:
//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Usage:
var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
In this way, the cursor is surely positioned at the end of the last element, eventually nested.
EDIT #1: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named void elements, and in this question there are some methods on how to test if an element is void. So, assuming that exists a function called canContainText that returns true if the argument is not a void element, the following line of code:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
should be replaced with:
canContainText(getLastChildElement(contentEditableElement))
EDIT #2: The above code is fully updated, with every changes described and discussed
It's possible to do set cursor to the end through the range:
setCaretToEnd(target/*: HTMLDivElement*/) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(target);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
target.focus();
range.detach(); // optimization
// set scroll to the end if multiline
target.scrollTop = target.scrollHeight;
}
A shorter and readable version using only selection (without range):
function setEndOfContenteditable(elem) {
let sel = window.getSelection();
sel.selectAllChildren(elem);
sel.collapseToEnd();
}
<p id="pdemo" contenteditable>
A paragraph <span id="txt1" style="background-color: #0903">span text node <i>span italic</i></span> a paragraph.
<p>
<button onclick="pdemo.focus(); setEndOfContenteditable(txt1)">set caret</button>
Quite useful: https://javascript.info/selection-range
Moving cursor to the end of editable span in response to focus event:
moveCursorToEnd(el){
if(el.innerText && document.createRange)
{
window.setTimeout(() =>
{
let selection = document.getSelection();
let range = document.createRange();
range.setStart(el.childNodes[0],el.innerText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
,1);
}
}
And calling it in event handler (React here):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
I had a similar problem trying to make a element editable. It was possible in Chrome and FireFox but in FireFox the caret either went to the beginning of the input or it went one space after the end of the input. Very confusing to the end-user I think, trying to edit the content.
I found no solution trying several things. Only thing that worked for me was to "go around the problem" by putting a plain old text-input INSIDE my . Now it works. Seems like "content-editable" is still bleeding edge tech, which may or may not work as you would like it to work, depending on the context.
The problem with contenteditable <div> and <span> is resolved when you start typing in it initially. One workaround for this could be triggering a focus event on your div element and on that function, clear, and refill what was already in the div element. This way the problem is resolved and finally you can place the cursor at the end using range and selection. Worked for me.
moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;
if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}
In HTML code:
<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>

Window text selection in a contenteditable

the text selection in a contenteditable causing me big problems...
I'm tryin to get begin and end selection point in the same way of this code part :
http://jsfiddle.net/TjXEG/1/
(Because in the contenteditable, there is differents tags and i need to reselect after a loss of focus the visible selected text (text node ?)
I'm really lost with that, someone know a tutorial or another thing to understand the selection in a web browser ?
Thanks,
Yeppao
Because I only use Chrome, I chopped off the else since it doesn't apply. So here's the Chrome solution:
Non-editable text. Editable is below:
<div id="test" contenteditable="true">Hello, some <b>bold</b> and <i>italic and <b>bold</b></i> text</div>
<div id="caretPos"></div>
<div id="caretPost"></div>
<script type="text/javascript">
function getCaretCharacterOffsetWithin(element) {
var begin = 0;
var end = 0;
if (typeof window.getSelection != "undefined") {
var range = window.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.startContainer, range.startOffset);
begin = preCaretRange.toString().length;
preCaretRange.setEnd(range.endContainer, range.endOffset);
end = preCaretRange.toString().length;
}
return "Selection start: " + begin + "<br>Selection end: " + end;
}
function showCaretPos() {
var el = document.getElementById("test");
var caretPosEl = document.getElementById("caretPos");
caretPosEl.innerHTML = getCaretCharacterOffsetWithin(el);
}
document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;
</script>
Once you understand it, the logic is pretty simple. There is a start and end container. If it is plain text: they will be the same; however, HTML tags fragment the sentence and will make start contain a portion and end contain a different portion.
If you use setStart() where I'm using setEnd() and reverse the parameters as well, it'll be the same as reversing the index (i.e. the end will be 0 instead of the beginning).
So in order to fetch the beginning, you still use setEnd(), except with the start parameters.

Problem with two JavaScript codes

I have these two codes -
new function($) {
$.fn.getCursorPosition = function() {
var pos = 0;
var el = $(this).get(0);
// IE Support
if (document.selection) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
pos = el.selectionStart;
return pos;
}
} (jQuery);
And
var element = document.getElementById('txtarr');
if( document.selection ){
// The current selection
var range = document.selection.createRange();
// We'll use this as a 'dummy'
var stored_range = range.duplicate();
// Select all text
stored_range.moveToElementText( element );
// Now move 'dummy' end point to end point of original range
stored_range.setEndPoint( 'EndToEnd', range );
// Now we can calculate start and end points
element.selectionStart = stored_range.text.length - range.text.length;
element.selectionEnd = element.selectionStart + range.text.length;
}
The first one is for getting the cursor position in a textarea and the second one is for determining the end of a textarea ,but they give the same result?
Where's the mistake?
I fix it.It's very simple :) .
I just replace the second code(for determining the end of the textarea) with:$("#txtarr").val().length(jQuery).#txtarr is the id of mine textarea.
Both pieces of code are doing the same thing in slightly different ways. Each is attempting to get the position of the caret or selection in a textarea (or text input), although the first only gets the start position of the selection while the second gets both the start and end positions.
Both have flaky inferences: the first assumes a browser featuring document.selection will support TextRange, while the second makes the same inference plus another that assumes a browser without support for document.selection will have support for selectionStart and selectionEnd properties of textareas. Neither will correctly handle line breaks in IE. For code that does that, see my answer here: How to get the start and end points of selection in text area?

Contenteditable text editor and cursor position

How can I (using jquery or other) insert html at the cursor/caret position of my contenteditable div:
<div contenteditable="true">Hello world</div>
For example, if the cursor/caret was between "hello" and "world" and the user then clicked a button, eg "insert image", then using javascript, something like <img src=etc etc> would be inserted between "hello" and "world". I hope I've made this clear =S
Example code would be greatly appreciated, thanks a lot!
The following function will insert a DOM node (element or text node) at the cursor position in all the mainstream desktop browsers:
function insertNodeAtCursor(node) {
var sel, range, html;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
sel.getRangeAt(0).insertNode(node);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data : node.outerHTML;
range.pasteHTML(html);
}
}
If you would rather insert an HTML string:
function insertHtmlAtCursor(html) {
var sel, range, node;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
}
}
I've adapted this from my answer to a similar question: How to find cursor position in a contenteditable DIV?
With contenteditable you should use execCommand.
Try document.execCommand('insertImage', false, 'image.jpg') or document.execCommand('insertHTML', false, '<img src="image.jpg" alt="" />'). The second doesn't work in older IE.
in this code i have just replace html code with (") to (')
use this syntax:
$("div.second").html("your html code and replace with (")to(') ");
I would recommend the use of the jquery plugin a-tools
This plugin has seven functions:
* getSelection – return start, end position, length of the selected text and the selected text. return start=end=caret position if text is not selected;
* replaceSelection – replace selected text with a given string;
* setSelection – select text in a given range (startPosition and endPosition);
* countCharacters – count amount of all characters;
* insertAtCaretPos – insert text at current caret position;
* setCaretPos – set cursor at caret position (1 = beginning, -1 = end);
* setMaxLength – set maximum length of input field. Also provides callback function if limit is reached. Note: The function has to have a number as input. Positive value for setting of limit and negative number for removing of limit.
The one that you need is insertAtCaretPos:
$("#textarea").insertAtCaretPos("<img src=etc etc>");
There might be a draw-back: this plugins only works with textarea en input:text elements, so there may be conflicts with contenteditable.

How to move cursor to end of contenteditable entity

I need to move caret to end of contenteditable node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable elements.
Geowa4's solution will work for a textarea, but not for a contenteditable element.
This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable.
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
It can be used by code similar to:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
If you don't care about older browsers, this one did the trick for me.
// [optional] make sure focus is on the element
yourContentEditableElement.focus();
// select all the content in the element
document.execCommand('selectAll', false, null);
// collapse selection to the end
document.getSelection().collapseToEnd();
There is also another problem.
The Nico Burns's solution works if the contenteditable div doesn't contain other multilined elements.
For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems.
In order to solve them, I've arranged the following solution, that is an improvement of the Nico's one:
//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Usage:
var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
In this way, the cursor is surely positioned at the end of the last element, eventually nested.
EDIT #1: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named void elements, and in this question there are some methods on how to test if an element is void. So, assuming that exists a function called canContainText that returns true if the argument is not a void element, the following line of code:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
should be replaced with:
canContainText(getLastChildElement(contentEditableElement))
EDIT #2: The above code is fully updated, with every changes described and discussed
It's possible to do set cursor to the end through the range:
setCaretToEnd(target/*: HTMLDivElement*/) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(target);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
target.focus();
range.detach(); // optimization
// set scroll to the end if multiline
target.scrollTop = target.scrollHeight;
}
A shorter and readable version using only selection (without range):
function setEndOfContenteditable(elem) {
let sel = window.getSelection();
sel.selectAllChildren(elem);
sel.collapseToEnd();
}
<p id="pdemo" contenteditable>
A paragraph <span id="txt1" style="background-color: #0903">span text node <i>span italic</i></span> a paragraph.
<p>
<button onclick="pdemo.focus(); setEndOfContenteditable(txt1)">set caret</button>
Quite useful: https://javascript.info/selection-range
Moving cursor to the end of editable span in response to focus event:
moveCursorToEnd(el){
if(el.innerText && document.createRange)
{
window.setTimeout(() =>
{
let selection = document.getSelection();
let range = document.createRange();
range.setStart(el.childNodes[0],el.innerText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
,1);
}
}
And calling it in event handler (React here):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
I had a similar problem trying to make a element editable. It was possible in Chrome and FireFox but in FireFox the caret either went to the beginning of the input or it went one space after the end of the input. Very confusing to the end-user I think, trying to edit the content.
I found no solution trying several things. Only thing that worked for me was to "go around the problem" by putting a plain old text-input INSIDE my . Now it works. Seems like "content-editable" is still bleeding edge tech, which may or may not work as you would like it to work, depending on the context.
The problem with contenteditable <div> and <span> is resolved when you start typing in it initially. One workaround for this could be triggering a focus event on your div element and on that function, clear, and refill what was already in the div element. This way the problem is resolved and finally you can place the cursor at the end using range and selection. Worked for me.
moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;
if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}
In HTML code:
<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>

Categories