Go to where word is highlighted - javascript

I have my app registering a highlighted word when I search in a html file through a UIWebview. The issue I have is the program is just highlighting the selected words. Since I have several pages, how do I make it so the program will automatically go to where the words are highlighted instead of me scrolling around, searching for the highlighted word. Here is my code so far. Thank you
function uiWebview_HighlightAllOccurencesOfStringForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
//if (counter < 1) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
//(value.split);
//we create a SPAN element for every parts of matched keywords
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor="yellow";
span.style.color="black";
uiWebview_SearchResultCount++; // update the counter
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}

// i used that code For Next and Previous Functionality And it works fine
// function
uiWebview_HighlightAllOccurencesOfNextStringForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
//if (counter < 1) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute("class","MyAppHighlight");
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx,value.length-idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span,next);
element.parentNode.insertBefore(text,next);
element = text;
span.scrollIntoView();
span.style.backgroundColor = "yellow";
span.style.color = "black";
a.push(span);
uiWebview_SearchResultCount++;
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
uiWebview_HighlightAllOccurencesOfNextStringForElement(element.childNodes[i],keyword);
}
}
}
}
}
// the main entry point to start the search
function uiWebview_HighlightAllOccurencesOfNextString(keyword)
`enter code here`{
uiWebview_RemoveAllHighlights();
uiWebview_HighlightAllOccurencesOfNextStringForElement(document.body, keyword.toLowerCase());
}
//And than In Your ViewContrlller Called this function on Next And Previous button method
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self highlightAllOccurencesOfNextString:searchbar.text];
}
- (NSInteger)highlightAllOccurencesOfNextString:(NSString*)str
{
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"UIWebViewSearch" ofType:#"js"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSString *jsString = [[NSMutableString alloc] initWithData:fileData encoding:NSUTF8StringEncoding];
[htmlWebView stringByEvaluatingJavaScriptFromString:jsString];
NSString *startSearch = [NSString stringWithFormat:#"uiWebview_HighlightAllOccurencesOfNextString('%#')",str];
[htmlWebView stringByEvaluatingJavaScriptFromString:startSearch];
NSString *result = [htmlWebView stringByEvaluatingJavaScriptFromString:#"a.length"];
currentPosition = [result intValue] - 1;
return [result integerValue];
}
-(void)nextMethod
{
currentPosition -= 1;
NSString *nextScrollPosition = [NSString stringWithFormat:#"a[%d].scrollIntoView()", currentPosition];
[htmlWebView stringByEvaluatingJavaScriptFromString:nextScrollPosition];
}
-(void)previousMethod
{
currentPosition += 1;
NSString *previousScrollPosition = [NSString stringWithFormat:#"a[%d].scrollIntoView()", currentPosition];
[htmlWebView stringByEvaluatingJavaScriptFromString:previousScrollPosition];
}

Related

Search and Highlight arabic characters text in UIWebView using JavaScript

I am using JavaScript to highlight the occurrence of characters in a UIWebView. I use the following JavaScript code:
var uiWebview_SearchResultCount = 0;
function uiWebview_HighlightAllOccurencesOfStringForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
while (true) {
//if (counter < 1) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
//(value.split);
//we create a SPAN element for every parts of matched keywords
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor="yellow";
span.style.color="black";
uiWebview_SearchResultCount++; // update the counter
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
window.scrollTo(0,span.offsetTop);
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}
// the main entry point to start the search
function uiWebview_HighlightAllOccurencesOfString(keyword) {
uiWebview_RemoveAllHighlights();
uiWebview_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
}
// helper function, recursively removes the highlights in elements and their childs
function uiWebview_RemoveAllHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "uiWebviewHighlight") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (uiWebview_RemoveAllHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
function uiWebview_RemoveAllHighlights() {
uiWebview_SearchResultCount = 0;
uiWebview_RemoveAllHighlightsForElement(document.body);
}
I then call this and everything works fine. My problem is that for characters that are in the middle of a word (for example و which is in the middle of توحید), it disconnects the و character from its previous character (and it becomes ت وحید).

Modify text in a contenteditable div without resetting the caret (cursor) position

I am trying to replace any instances of /any thing in here/ with <b>/any thing in here/</b> on the fly, as changes are made in a contenteditable div.
My current implementation works, but at every keypress the caret is moved to the beginning of div making the implementation unusable. Is there some way to keep the caret position while replacing the div's contents?
$('.writer').on('keyup', function(e) {
$(this).html($(this).html().replace(/\/(.*)\//g, '<b>\/$1\/<\/b>'));
});
try it demo
$('#writer').on('keyup', function(e) {
var range = window.getSelection().getRangeAt(0);
var end_node = range.endContainer;
var end = range.endOffset;
if(end_node != this){
var text_nodes = get_text_nodes_in(this);
for (var i = 0; i < text_nodes.length; ++i) {
if(text_nodes[i] == end_node){
break;
}
end += text_nodes[i].length;
}
}
var html = $(this).html();
if(/\ $/.test(html) && $(this).text().length == end){
end = end - 1;
set_range(end,end,this);
return;
}
var filter = html.replace(/(<b>)?\/([^<\/]*)(<\/b>)?/g, '\/$2');
console.log(filter);
filter = filter.replace(/(<b>)?([^<\/]*)\/(<\/b>)?/g, '$2\/');
console.log(filter);
filter = filter.replace(/(<b>)?\/([^<\/]*)\/(<\/b>)?/g, '<b>\/$2\/<\/b>');
console.log(filter);
if(!/\ $/.test($(this).html())){
filter += ' ';
}
$(this).html(filter);
set_range(end,end,this);
});
$('#writer').on('mouseup', function(e) {
if(!/\ $/.test($(this).html())){
return;
}
var range = window.getSelection().getRangeAt(0);
var end = range.endOffset;
var end_node = range.endContainer;
if(end_node != this){
var text_nodes = get_text_nodes_in(this);
for (var i = 0; i < text_nodes.length; ++i) {
if(text_nodes[i] == end_node){
break;
}
end += text_nodes[i].length;
}
}
if($(this).text().length == end){
end = end - 1;
set_range(end,end,this);
}
});
function get_text_nodes_in(node) {
var text_nodes = [];
if (node.nodeType === 3) {
text_nodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
var text_node
text_nodes.push.apply(text_nodes, get_text_nodes_in(children[i]));
}
}
return text_nodes;
}
function set_range(start, end, element) {
var range = document.createRange();
range.selectNodeContents(element);
var text_nodes = get_text_nodes_in(element);
var foundStart = false;
var char_count = 0, end_char_count;
for (var i = 0, text_node; text_node = text_nodes[i++]; ) {
end_char_count = char_count + text_node.length;
if (!foundStart && start >= char_count && (start < end_char_count || (start === end_char_count && i < text_nodes.length))) {
range.setStart(text_node, start - char_count);
foundStart = true;
}
if (foundStart && end <= end_char_count) {
range.setEnd(text_node, end - char_count);
break;
}
char_count = end_char_count;
}
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}

Getting deleted character or text on pressing delete or backspace on a textbox

I have a text box, I want to get the deleted character when I press a backspace or delete key.
I have a key up event handler and i am capturing if the key is backspace. Now inside this I need to perform some tasks based on the key deleted. Please help.
After making a little tweak for the getCursorPosition function in this thread, you can get the characters deleted by tracking the current cursor selection.
The code handles the following conditions:
Type and then backspace at the end.
Move cursor in the middle of the text and delete/backspace.
Select a piece of text and then delete/backspace.
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
var posEnd = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if('selection' in document) {
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;
posEnd = Sel.text.length;
}
// return both selection start and end;
return [pos, posEnd];
};
$('#text').keydown(function (e) {
var position = $(this).getCursorPosition();
var deleted = '';
var val = $(this).val();
if (e.which == 8) {
if (position[0] == position[1]) {
if (position[0] == 0)
deleted = '';
else
deleted = val.substr(position[0] - 1, 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
else if (e.which == 46) {
var val = $(this).val();
if (position[0] == position[1]) {
if (position[0] === val.length)
deleted = '';
else
deleted = val.substr(position[0], 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
// Now you can test the deleted character(s) here
});
And here is Live Demo
You could use the keydown event handler instead so that the last character to be deleted is still available:
$('textarea').on('keydown',function(e) {
var deleteKeyCode = 8,
value = $(this).val(),
length = value.length,
lastChar = value.substring(length-1, length);
if (e.which === deleteKeyCode) {
alert(lastChar);
}
});
Live Demo
$('input').keydown(function(e){
$(this).data('prevVal', $(this).val());
}).keyup(function(e){
if(e.keyCode === 8) {//delete
var ele = $(this);
var val = ele.data('prevVal');
var newVal = ele.val();
var removedChar = val.substring(val.length-1);
alert(removedChar);
}
});

How to select line of text in textarea

I have a textarea that is used to hold massive SQL scripts for parsing. When the user clicks the "Parse" button, they get summary information on the SQL script.
I'd like the summary information to be clickable so that when it's clicked, the line of the SQL script is highlighted in the textarea.
I already have the line number in the output so all I need is the javascript or jquery that tells it which line of the textarea to highlight.
Is there some type of "goToLine" function? In all my searching, nothing quite addresses what I'm looking for.
This function expects first parameter to be reference to your textarea and second parameter to be the line number
function selectTextareaLine(tarea,lineNum) {
lineNum--; // array starts at 0
var lines = tarea.value.split("\n");
// calculate start/end
var startPos = 0, endPos = tarea.value.length;
for(var x = 0; x < lines.length; x++) {
if(x == lineNum) {
break;
}
startPos += (lines[x].length+1);
}
var endPos = lines[lineNum].length+startPos;
// do selection
// 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;
}
return false;
}
Usage:
var tarea = document.getElementById('myTextarea');
selectTextareaLine(tarea,3); // selects line 3
Working example:
http://jsfiddle.net/5enfp/
A somewhat neater version of the search for lines:
function select_textarea_line (ta, line_index) {
const newlines = [-1]; // Index of imaginary \n before first line
for (let i = 0; i < ta.value.length; ++i) {
if (ta.value[i] == '\n') newlines.push( i );
}
ta.focus();
ta.selectionStart = newlines[line_index] + 1;
ta.selectionEnd = newlines[line_index + 1];
} // select_textarea_line
Add a onclick or ondblclick event handler to your <textarea>:
<textarea onclick="onClickSelectLine(this)"></textarea>
And JavaScript function to handle the onclick event:
/**
* onclick event for TextArea to select the whole line
* #param textarea {HTMLTextAreaElement}
* #returns {boolean}
*/
function onClickSelectLine(textarea) {
if (typeof textarea.selectionStart == 'undefined') {
return false
}
let text = textarea.value
let before = text.substring(0, textarea.selectionStart)
let after = text.substring(textarea.selectionEnd, text.length);
let startPos = before.lastIndexOf("\n") >= 0 ? before.lastIndexOf("\n") + 1 : 0
let endPos = after.indexOf("\n") >= 0 ? textarea.selectionEnd + after.indexOf("\n") : text.length
textarea.selectionStart = startPos
textarea.selectionEnd = endPos
return true
}
To make the function more forgiving on possible faulty input add after:
// array starts at 0
lineNum--;
This code:
if (typeof(tarea) !== 'object' || typeof(tarea.value) !== 'string') {
return false;
}
if (lineNum === 'undefined' || lineNum == null || lineNum < 0) {
lineNum = 0;
}
How to select line of text in textarea javascript double click on particular line.
//This function expects first parameter to be reference to your textarea.
function ondblClickSelection(textarea){
var startPos = 0;
var lineNumber = 0;
var content = "";
if(typeof textarea.selectionStart == 'undefined') {
return false;
}
startPos = textarea.selectionStart;
endPos = textarea.value.length;
lineNumber = textarea.value.substr(0,startPos).split("\n").length - 1;
content = textarea.value.split("\n")[lineNumber];
var lines = textarea.value.split("\n");
var endPos = lines[lineNumber].length+startPos;
textarea.selectionStart = startPos;
textarea.selectionEnd = endPos;
return true;
}

How to set the caret (cursor) position in a contenteditable element (div)?

I have this simple HTML as an example:
<div id="editable" contenteditable="true">
text text text<br>
text text text<br>
text text text<br>
</div>
<button id="button">focus</button>
I want simple thing - when I click the button, I want to place caret(cursor) into specific place in the editable div. From searching over the web, I have this JS attached to button click, but it doesn't work (FF, Chrome):
const range = document.createRange();
const myDiv = document.getElementById("editable");
range.setStart(myDiv, 5);
range.setEnd(myDiv, 5);
Is it possible to set manually caret position like this?
In most browsers, you need the Range and Selection objects. You specify each of the selection boundaries as a node and an offset within that node. For example, to set the caret to the fifth character of the second line of text, you'd do the following:
function setCaret() {
var el = document.getElementById("editable")
var range = document.createRange()
var sel = window.getSelection()
range.setStart(el.childNodes[2], 5)
range.collapse(true)
sel.removeAllRanges()
sel.addRange(range)
}
<div id="editable" contenteditable="true">
text text text<br>text text text<br>text text text<br>
</div>
<button id="button" onclick="setCaret()">focus</button>
IE < 9 works completely differently. If you need to support these browsers, you'll need different code.
jsFiddle example: http://jsfiddle.net/timdown/vXnCM/
Most answers you find on contenteditable cursor positioning are fairly simplistic in that they only cater for inputs with plain vanilla text. Once you using html elements within the container the text entered gets split into nodes and distributed liberally across a tree structure.
To set the cursor position I have this function which loops round all the child text nodes within the supplied node and sets a range from the start of the initial node to the chars.count character:
function createRange(node, chars, range) {
if (!range) {
range = document.createRange()
range.selectNode(node);
range.setStart(node, 0);
}
if (chars.count === 0) {
range.setEnd(node, chars.count);
} else if (node && chars.count >0) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.length < chars.count) {
chars.count -= node.textContent.length;
} else {
range.setEnd(node, chars.count);
chars.count = 0;
}
} else {
for (var lp = 0; lp < node.childNodes.length; lp++) {
range = createRange(node.childNodes[lp], chars, range);
if (chars.count === 0) {
break;
}
}
}
}
return range;
};
I then call the routine with this function:
function setCurrentCursorPosition(chars) {
if (chars >= 0) {
var selection = window.getSelection();
range = createRange(document.getElementById("test").parentNode, { count: chars });
if (range) {
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
}
};
The range.collapse(false) sets the cursor to the end of the range. I've tested it with the latest versions of Chrome, IE, Mozilla and Opera and they all work fine.
PS. If anyone is interested I get the current cursor position using this code:
function isChildOf(node, parentId) {
while (node !== null) {
if (node.id === parentId) {
return true;
}
node = node.parentNode;
}
return false;
};
function getCurrentCursorPosition(parentId) {
var selection = window.getSelection(),
charCount = -1,
node;
if (selection.focusNode) {
if (isChildOf(selection.focusNode, parentId)) {
node = selection.focusNode;
charCount = selection.focusOffset;
while (node) {
if (node.id === parentId) {
break;
}
if (node.previousSibling) {
node = node.previousSibling;
charCount += node.textContent.length;
} else {
node = node.parentNode;
if (node === null) {
break
}
}
}
}
}
return charCount;
};
The code does the opposite of the set function - it gets the current window.getSelection().focusNode and focusOffset and counts backwards all text characters encountered until it hits a parent node with id of containerId. The isChildOf function just checks before running that the suplied node is actually a child of the supplied parentId.
The code should work straight without change, but I have just taken it from a jQuery plugin I've developed so have hacked out a couple of this's - let me know if anything doesn't work!
I refactored #Liam's answer. I put it in a class with static methods, I made its functions receive an element instead of an #id, and some other small tweaks.
This code is particularly good for fixing the cursor in a rich text box that you might be making with <div contenteditable="true">. I was stuck on this for several days before arriving at the below code.
edit: His answer and this answer have a bug involving hitting enter. Since enter doesn't count as a character, the cursor position gets messed up after hitting enter. If I am able to fix the code, I will update my answer.
edit2: Save yourself a lot of headaches and make sure your <div contenteditable=true> is display: inline-block. This fixes some bugs related to Chrome putting <div> instead of <br> when you press enter.
How To Use
let richText = document.getElementById('rich-text');
let offset = Cursor.getCurrentCursorPosition(richText);
// insert code here that does stuff to the innerHTML, such as adding/removing <span> tags
Cursor.setCurrentCursorPosition(offset, richText);
richText.focus();
Code
// Credit to Liam (Stack Overflow)
// https://stackoverflow.com/a/41034697/3480193
class Cursor {
static getCurrentCursorPosition(parentElement) {
var selection = window.getSelection(),
charCount = -1,
node;
if (selection.focusNode) {
if (Cursor._isChildOf(selection.focusNode, parentElement)) {
node = selection.focusNode;
charCount = selection.focusOffset;
while (node) {
if (node === parentElement) {
break;
}
if (node.previousSibling) {
node = node.previousSibling;
charCount += node.textContent.length;
} else {
node = node.parentNode;
if (node === null) {
break;
}
}
}
}
}
return charCount;
}
static setCurrentCursorPosition(chars, element) {
if (chars >= 0) {
var selection = window.getSelection();
let range = Cursor._createRange(element, { count: chars });
if (range) {
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}
}
}
static _createRange(node, chars, range) {
if (!range) {
range = document.createRange()
range.selectNode(node);
range.setStart(node, 0);
}
if (chars.count === 0) {
range.setEnd(node, chars.count);
} else if (node && chars.count >0) {
if (node.nodeType === Node.TEXT_NODE) {
if (node.textContent.length < chars.count) {
chars.count -= node.textContent.length;
} else {
range.setEnd(node, chars.count);
chars.count = 0;
}
} else {
for (var lp = 0; lp < node.childNodes.length; lp++) {
range = Cursor._createRange(node.childNodes[lp], chars, range);
if (chars.count === 0) {
break;
}
}
}
}
return range;
}
static _isChildOf(node, parentElement) {
while (node !== null) {
if (node === parentElement) {
return true;
}
node = node.parentNode;
}
return false;
}
}
I made this for my simple text editor.
Differences from other methods:
High performance
Works with all spaces
usage
// get current selection
const [start, end] = getSelectionOffset(container)
// change container html
container.innerHTML = newHtml
// restore selection
setSelectionOffset(container, start, end)
// use this instead innerText for get text with keep all spaces
const innerText = getInnerText(container)
const textBeforeCaret = innerText.substring(0, start)
const textAfterCaret = innerText.substring(start)
selection.ts
/** return true if node found */
function searchNode(
container: Node,
startNode: Node,
predicate: (node: Node) => boolean,
excludeSibling?: boolean,
): boolean {
if (predicate(startNode as Text)) {
return true
}
for (let i = 0, len = startNode.childNodes.length; i < len; i++) {
if (searchNode(startNode, startNode.childNodes[i], predicate, true)) {
return true
}
}
if (!excludeSibling) {
let parentNode = startNode
while (parentNode && parentNode !== container) {
let nextSibling = parentNode.nextSibling
while (nextSibling) {
if (searchNode(container, nextSibling, predicate, true)) {
return true
}
nextSibling = nextSibling.nextSibling
}
parentNode = parentNode.parentNode
}
}
return false
}
function createRange(container: Node, start: number, end: number): Range {
let startNode
searchNode(container, container, node => {
if (node.nodeType === Node.TEXT_NODE) {
const dataLength = (node as Text).data.length
if (start <= dataLength) {
startNode = node
return true
}
start -= dataLength
end -= dataLength
return false
}
})
let endNode
if (startNode) {
searchNode(container, startNode, node => {
if (node.nodeType === Node.TEXT_NODE) {
const dataLength = (node as Text).data.length
if (end <= dataLength) {
endNode = node
return true
}
end -= dataLength
return false
}
})
}
const range = document.createRange()
if (startNode) {
if (start < startNode.data.length) {
range.setStart(startNode, start)
} else {
range.setStartAfter(startNode)
}
} else {
if (start === 0) {
range.setStart(container, 0)
} else {
range.setStartAfter(container)
}
}
if (endNode) {
if (end < endNode.data.length) {
range.setEnd(endNode, end)
} else {
range.setEndAfter(endNode)
}
} else {
if (end === 0) {
range.setEnd(container, 0)
} else {
range.setEndAfter(container)
}
}
return range
}
export function setSelectionOffset(node: Node, start: number, end: number) {
const range = createRange(node, start, end)
const selection = window.getSelection()
selection.removeAllRanges()
selection.addRange(range)
}
function hasChild(container: Node, node: Node): boolean {
while (node) {
if (node === container) {
return true
}
node = node.parentNode
}
return false
}
function getAbsoluteOffset(container: Node, offset: number) {
if (container.nodeType === Node.TEXT_NODE) {
return offset
}
let absoluteOffset = 0
for (let i = 0, len = Math.min(container.childNodes.length, offset); i < len; i++) {
const childNode = container.childNodes[i]
searchNode(childNode, childNode, node => {
if (node.nodeType === Node.TEXT_NODE) {
absoluteOffset += (node as Text).data.length
}
return false
})
}
return absoluteOffset
}
export function getSelectionOffset(container: Node): [number, number] {
let start = 0
let end = 0
const selection = window.getSelection()
for (let i = 0, len = selection.rangeCount; i < len; i++) {
const range = selection.getRangeAt(i)
if (range.intersectsNode(container)) {
const startNode = range.startContainer
searchNode(container, container, node => {
if (startNode === node) {
start += getAbsoluteOffset(node, range.startOffset)
return true
}
const dataLength = node.nodeType === Node.TEXT_NODE
? (node as Text).data.length
: 0
start += dataLength
end += dataLength
return false
})
const endNode = range.endContainer
searchNode(container, startNode, node => {
if (endNode === node) {
end += getAbsoluteOffset(node, range.endOffset)
return true
}
const dataLength = node.nodeType === Node.TEXT_NODE
? (node as Text).data.length
: 0
end += dataLength
return false
})
break
}
}
return [start, end]
}
export function getInnerText(container: Node) {
const buffer = []
searchNode(container, container, node => {
if (node.nodeType === Node.TEXT_NODE) {
buffer.push((node as Text).data)
}
return false
})
return buffer.join('')
}
I'm writting a syntax highlighter (and basic code editor), and I needed to know how to auto-type a single quote char and move the caret back (like a lot of code editors nowadays).
Heres a snippet of my solution, thanks to much help from this thread, the MDN docs, and a lot of moz console watching..
//onKeyPress event
if (evt.key === "\"") {
let sel = window.getSelection();
let offset = sel.focusOffset;
let focus = sel.focusNode;
focus.textContent += "\""; //setting div's innerText directly creates new
//nodes, which invalidate our selections, so we modify the focusNode directly
let range = document.createRange();
range.selectNode(focus);
range.setStart(focus, offset);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
//end onKeyPress event
This is in a contenteditable div element
I leave this here as a thanks, realizing there is already an accepted answer.
const el = document.getElementById("editable");
el.focus()
let char = 1, sel; // character at which to place caret
if (document.selection) {
sel = document.selection.createRange();
sel.moveStart('character', char);
sel.select();
}
else {
sel = window.getSelection();
sel.collapse(el.lastChild, char);
}
If you don't want to use jQuery you can try this approach:
public setCaretPosition() {
const editableDiv = document.getElementById('contenteditablediv');
const lastLine = this.input.nativeElement.innerHTML.replace(/.*?(<br>)/g, '');
const selection = window.getSelection();
selection.collapse(editableDiv.childNodes[editableDiv.childNodes.length - 1], lastLine.length);
}
editableDiv you editable element, don't forget to set an id for it. Then you need to get your innerHTML from the element and cut all brake lines. And just set collapse with next arguments.
function set_mouse() {
var as = document.getElementById("editable");
el = as.childNodes[1].childNodes[0]; //goal is to get ('we') id to write (object Text) because it work only in object text
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el, 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
document.getElementById("we").innerHTML = el; // see out put of we id
}
<div id="editable" contenteditable="true">dddddddddddddddddddddddddddd
<p>dd</p>psss
<p>dd</p>
<p>dd</p>
<p>text text text</p>
</div>
<p id='we'></p>
<button onclick="set_mouse()">focus</button>
It is very hard set caret in proper position when you have advance element like (p) (span) etc. The goal is to get (object text):
<div id="editable" contenteditable="true">dddddddddddddddddddddddddddd<p>dd</p>psss<p>dd</p>
<p>dd</p>
<p>text text text</p>
</div>
<p id='we'></p>
<button onclick="set_mouse()">focus</button>
<script>
function set_mouse() {
var as = document.getElementById("editable");
el = as.childNodes[1].childNodes[0];//goal is to get ('we') id to write (object Text) because it work only in object text
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el, 1);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
document.getElementById("we").innerHTML = el;// see out put of we id
}
</script>
I think it's not simple to set caret to some position in contenteditable element. I wrote my own code for this. It bypasses the node tree calcing how many characters left and sets caret in needed element. I didn't test this code much.
//Set offset in current contenteditable field (for start by default or for with forEnd=true)
function setCurSelectionOffset(offset, forEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return;
const firstRange = sel.getRangeAt(0);
if (offset > 0) {
bypassChildNodes(document.activeElement, offset);
}else{
if (forEnd)
firstRange.setEnd(document.activeElement, 0);
else
firstRange.setStart(document.activeElement, 0);
}
//Bypass in depth
function bypassChildNodes(el, leftOffset) {
const childNodes = el.childNodes;
for (let i = 0; i < childNodes.length && leftOffset; i++) {
const childNode = childNodes[i];
if (childNode.nodeType === 3) {
const curLen = childNode.textContent.length;
if (curLen >= leftOffset) {
if (forEnd)
firstRange.setEnd(childNode, leftOffset);
else
firstRange.setStart(childNode, leftOffset);
return 0;
}else{
leftOffset -= curLen;
}
}else
if (childNode.nodeType === 1) {
leftOffset = bypassChildNodes(childNode, leftOffset);
}
}
return leftOffset;
}
}
I also wrote code to get current caret position (didn't test):
//Get offset in current contenteditable field (start offset by default or end offset with calcEnd=true)
function getCurSelectionOffset(calcEnd = false) {
const sel = window.getSelection();
if (sel.rangeCount !== 1 || !document.activeElement) return 0;
const firstRange = sel.getRangeAt(0),
startContainer = calcEnd ? firstRange.endContainer : firstRange.startContainer,
startOffset = calcEnd ? firstRange.endOffset : firstRange.startOffset;
let needStop = false;
return bypassChildNodes(document.activeElement);
//Bypass in depth
function bypassChildNodes(el) {
const childNodes = el.childNodes;
let ans = 0;
if (el === startContainer) {
if (startContainer.nodeType === 3) {
ans = startOffset;
}else
if (startContainer.nodeType === 1) {
for (let i = 0; i < startOffset; i++) {
const childNode = childNodes[i];
ans += childNode.nodeType === 3 ? childNode.textContent.length :
childNode.nodeType === 1 ? childNode.innerText.length :
0;
}
}
needStop = true;
}else{
for (let i = 0; i < childNodes.length && !needStop; i++) {
const childNode = childNodes[i];
ans += bypassChildNodes(childNode);
}
}
return ans;
}
}
You also need to be aware of range.startOffset and range.endOffset contain character offset for text nodes (nodeType === 3) and child node offset for element nodes (nodeType === 1). range.startContainer and range.endContainer may refer to any element node of any level in the tree (of course they also can refer to text nodes).
Based on Tim Down's answer, but it checks for the last known "good" text row. It places the cursor at the very end.
Furthermore, I could also recursively/iteratively check the last child of each consecutive last child to find the absolute last "good" text node in the DOM.
function onClickHandler() {
setCaret(document.getElementById("editable"));
}
function setCaret(el) {
let range = document.createRange(),
sel = window.getSelection(),
lastKnownIndex = -1;
for (let i = 0; i < el.childNodes.length; i++) {
if (isTextNodeAndContentNoEmpty(el.childNodes[i])) {
lastKnownIndex = i;
}
}
if (lastKnownIndex === -1) {
throw new Error('Could not find valid text content');
}
let row = el.childNodes[lastKnownIndex],
col = row.textContent.length;
range.setStart(row, col);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
function isTextNodeAndContentNoEmpty(node) {
return node.nodeType == Node.TEXT_NODE && node.textContent.trim().length > 0
}
<div id="editable" contenteditable="true">
text text text<br>text text text<br>text text text<br>
</div>
<button id="button" onclick="onClickHandler()">focus</button>
var sel = window.getSelection();
sel?.setPosition(wordDiv.childNodes[0], 5);
event.preventDefault();
move(element:any,x:number){//parent
let arr:Array<any>=[];
arr=this.getAllnodeOfanItem(this.input.nativeElement,arr);
let j=0;
while (x>arr[j].length && j<arr.length){
x-=arr[j].length;
j++;
}
var el = arr[j];
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el,x );
range.collapse(true);
if (sel)sel.removeAllRanges();
if (sel)sel.addRange(range);
}
getAllnodeOfanItem(element:any,rep:Array<any>){
let ch:Array<any>=element.childNodes;
if (ch.length==0 && element.innerText!="")
rep.push(element);
else{
for (let i=0;i<ch.length;i++){
rep=this.getAllnodeOfanItem(ch[i],rep)
}
}
return rep;
}
I've readed and tried some cases from here and just put here what is working for me, considering some details according dom nodes:
focus(textInput){
const length = textInput.innerText.length;
textInput.focus();
if(!!textInput.lastChild){
const sel = window.getSelection();
sel.collapse(textInput.lastChild, length);
}
}

Categories

Resources