get and set cursor position in content editable div - javascript

in a content editable div, i wish get and set cursor position but but without taking into account the child elements (, , etc for example).
for get, i find this solution : Get a range's start and end offset's relative to its parent container
but for set, i don't know.
please, can u help me.
thank u

You can use rangy to define it yourself, just like this:
var selector = document.querySelector('[contenteditable]');
var setCaretIndex = function (index) {
var charIndex = 0, stop = {};
var traverseNodes = function (node) {
if (node.nodeType === 3) {
var nextCharIndex = charIndex + node.length;
if (index >= charIndex && index <= nextCharIndex) {
rangy.getSelection().collapse(node, index - charIndex);
throw stop;
}
charIndex = nextCharIndex;
}
// Count an empty element as a single character. The list below may not be exhaustive.
else if (node.nodeType === 1 && /^(input|br|img|col|area|link|meta|link|param|base)$/i.test(node.nodeName)) {
charIndex += 1;
} else {
var child = node.firstChild;
while (child) {
traverseNodes(child);
child = child.nextSibling;
}
}
};
try {
traverseNodes(selector);
} catch (ex) {
if (ex !== stop) throw ex;
}
};
To use this function, you need to focus the editor first:
selector.focus();
Then giving an index to set cursor position:
setCaretIndex(3);
Fiddle

Related

How can I get the line that is being clicked on in a contenteditable environment?

I'm new to HTML/JS and I'm trying to make a text editor as a small project.
Please forgive me if I'm not explaining my thoughts clearly.
Let's say I have the following text in my contenteditable div environment, and let | represent the cursor (as it would look in most editors):
hi this is some text
here is some mor|e text
hello, world!
How would I be able to return the text "here is some more text"?
I'm using jQuery and I was thinking I want to use the onClick handler, but that doesn't respond to the arrow keys being used to navigate. What kind of event handler would I need? So far, I've parsed the text to replace the div separators, but I'm a bit lost on how to proceed.
What would you suggest doing? (General links/advice also work, I'm trying to learn more through this project)
Edit, here's my html:
<div id="editor" class="editor" contenteditable="true"></div>
here's the JS:
$(document).on('keydown', '.editor', function(e){
//detect 'tab' key
if(e.keyCode == 9){
//add tab
document.execCommand('insertHTML', false, '&#009');
//prevent focusing on next element
e.preventDefault()
}
var text = $("#editor").html();
console.log("MYLITERAL:" + text);
// parse the string :)
// for the div tags, replacing them with \n
var tmp = text.replace(/<div>/g, "");
tmp = tmp.replace(/<\/div>/g, "");
tmp = tmp.replace(/<br>/g, "\n");
console.log(tmp);
document.getElementById("demo").innerHTML = tmp;
});
You can try the following:
var strO, endO, lstEle;
function selectRange(start, end, this_){
var el = this_,sPos = start,ePos = end;
var charIndex = 0, range = document.createRange();
range.setStart(el, 0);
range.collapse(true);
var nodeStack = [el], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && sPos >= charIndex && sPos <= nextCharIndex) {
range.setStart(node, sPos - charIndex);
foundStart = true;
}
if (foundStart && ePos >= charIndex && ePos <= nextCharIndex) {
range.setEnd(node, ePos - charIndex);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var s = (window.getSelection) ? window.getSelection() : document.selection;
if(window.getSelection) {
s.removeAllRanges();
s.addRange(range);
} else {
range.select();
}
}
// node_walk: walk the element tree, stop when func(node) returns false
function node_walk(node, func) {
var result = func(node);
for(node = node.firstChild; result !== false && node; node = node.nextSibling){
result = node_walk(node, func);
lstEle = node;
}
return result;
};
// getCaretPosition: return [start, end] as offsets to elem.textContent that
// correspond to the selected portion of text
// (if start == end, caret is at given position and no text is selected)
function getCaretPosition(elem) {
strO = 0, endO = 0, lstEle = elem;
var sel = window.getSelection();
var cum_length = [0, 0];
if(sel.anchorNode == elem)
cum_length = [sel.anchorOffset, sel.extentOffset];
else {
var nodes_to_find = [sel.anchorNode, sel.extentNode];
if(!elem.contains(sel.anchorNode) || !elem.contains(sel.extentNode))
return undefined;
else {
var found = [0,0];
var i;
node_walk(elem, function(node) {
for(i = 0; i < 2; i++) {
if(node == nodes_to_find[i]) {
found[i] = true;
if(found[i == 0 ? 1 : 0])
return false; // all done
}
}
if(node.textContent && !node.firstChild) {
for(i = 0; i < 2; i++) {
if(!found[i])
cum_length[i] += node.textContent.length;
}
}
});
strO = cum_length[0];
endO = strO + lstEle.textContent.length;
cum_length[0] += sel.anchorOffset;
cum_length[1] += sel.extentOffset;
}
}
if(cum_length[0] <= cum_length[1])
return cum_length;
return [cum_length[1], cum_length[0]];
}
var update = function() {
$('#test').html(getCaretPosition(this)+' '+strO+' '+endO);
selectRange(strO, endO, this);
$('#test').append('<br>'+window.getSelection().toString());
};
$('#editor').on("mouseup keydown keyup", update);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="editor" class="editor" contenteditable="true">hi this is some text<br>here is some more text<br>hello, world!</div>
<div id="test">test</div>

Convert first letter to uppercase on input box

JS Bin demo
This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.
I have no idea how to properly replace the selected characters in the current input field.
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
// I want this value to be in the input field.
console.log(val);
});
Given i.e: const str = "hello world" to become Hello world
const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);
or:
const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);
or:
const firstUpper = str[0] + str.substr(1);
input {
text-transform: capitalize;
}
http://jsfiddle.net/yuMZq/1/
Using text-transform would be better.
You can convert the first letter to Uppercase and still avoid the annoying problem of the cursor jumping to the beginning of the line, by checking the caret position and resetting the caret position. I do this on a form by defining a few functions, one for all Uppercase, one for Proper Case, one for only Initial Uppercase... Then two functions for the Caret Position, one that gets and one that sets:
function ProperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g,
function($1) { return $1.toUpperCase(); });
$(el).val(s);
setCaretPosition(el,pos.start);
}
function UpperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toUpperCase();
$(el).val(s);
setCaretPosition(el,pos.start);
}
function initialCap(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.substr(0, 1).toUpperCase() + s.substr(1);
$(el).val(s);
setCaretPosition(el,pos.start);
}
/* GETS CARET POSITION */
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
Then on document ready I apply a keyup event listener to the fields I want to be checked, but I only listen for keys that can actually modify the content of the field (I skip "Shift" key for example...), and if user hits "Esc" I restore the original value of the field...
$('.updatablefield', $('#myform')).keyup(function(e) {
myfield=this.id;
myfieldname=this.name;
el = document.getElementById(myfield);
// or the jquery way:
// el = $(this)[0];
if (e.keyCode == 27) { // if esc character is pressed
$('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end if (e.keyCode == 27)
// if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end else = if any other character is pressed //
}); // end $(document).keyup(function(e)
You can see a working fiddle of this example here: http://jsfiddle.net/ZSDXA/
Simply put:
$this.val(val);
$(document).ready(function() {
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
console.log(val);
$this.val(val);
});
});
As #roXon has shown though, this can be simplified:
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
An alternative, and better solution in my opinion, would be to only style the element as being capitalized, and then do your logic server side.
This removes the overhead of any javascript, and ensures the logic is handled server side (which it should be anyway!)
$('input').on('keyup', function(event) {
$(this).val(function(i, v){
return v.replace(/[a-zA-Z]/, function(c){
return c.toUpperCase();
})
})
});
http://jsfiddle.net/AbxVx/
This will do for every textfield call function on keyup
where id is id of your textfield and value is value you type in textfield
function capitalizeFirstLetter(value,id)
{
if(value.length>0){
var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
document.getElementById(id).value=str;
}
}
only use this This work for first name in capital char
style="text-transform:capitalize;
Like
<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
$('.form-capitalize').keyup(function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
this.value = val;
// I want this value to be in the input field.
console.log(val);
});

Rangy loses caret position on backspace in contenteditable div

I have researched all the Rangy Q&As for days but could not adapt anything to this case.
I have the following contenteditable
<div id="area" style="width:100%;height:2em;"
contentEditable="true";
onkeyup="formatText();"
></div>
calling a function that every time the user types something, it parses the content and formats specific tokens.
function formatText() {
var el = document.getElementById('area');
var savedSel = saveSelection(el); // calls Rangy function
var tokenColor;
// removes html tags before passing the expression to the parser
var userInput = document.getElementById('area').innerHTML.replace(/(<([^>]+)>)/g,"").replace(/&/g, "").replace(/>/g, ">").replace(/</g, "<").replace(/<span[^>]*>+<\/span>/, "");
var i, newHTML=[];
tokenType=[]; // [NUMBER,+,(,NUMBER,..]
tokenArray=[]; // [3,+,(5,...]
var resultOutput = parse(userInput); // parser also fills tokenType and tokenArray
for (i=0; i<tokenArray.length-1; i++){
newHTML += "<span style='color: " + tokenColor + " '>" + tokenArray[i] + "</span>";
} // newHTML looks like <span style='color: red'>3</span><span style='color: black'>+</span> etc.
el.innerHTML = newHTML; // replaces content of <div> with formatted text
restoreSelection(el, savedSel); // calls Rangy function to restore cursor position
}
I use the following Rangy based functions presented by the author in other posts on this forum:
function saveSelection(containerEl) {
var charIndex = 0, start = 0, end = 0, foundStart = false, stop = {};
var sel = rangy.getSelection(), range;
function traverseTextNodes(node, range) {
if (node.nodeType == 3) {
if (!foundStart && node == range.startContainer) {
start = charIndex + range.startOffset;
foundStart = true;
}
if (foundStart && node == range.endContainer) {
end = charIndex + range.endOffset;
throw stop;
}
charIndex += node.length;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i], range);
}
}
}
if (sel.rangeCount) {
try {
traverseTextNodes(containerEl, sel.getRangeAt(0));
} catch (ex) {
if (ex != stop) {
throw ex;
}
}
}
return {
start: start,
end: end
};
}
function restoreSelection(containerEl, savedSel) {
var charIndex = 0, range = rangy.createRange(), foundStart = false, stop = {};
range.collapseToPoint(containerEl, 0);
function traverseTextNodes(node) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
throw stop;
}
charIndex = nextCharIndex;
}
else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i]);
}
}
}
try {
traverseTextNodes(containerEl);
} catch (ex) {
if (ex == stop) {
rangy.getSelection().setSingleRange(range);
} else {
throw ex;
}
}
}
Everything works perfectly until I try to delete a character. At that point, the cursor jumps at the beginning of the div.
Any idea of why this could happen?
Many thanks.
I have solved the problem with Tim Down's help (thanks Tim!).
He has recently added the new TextRange module to Rangy and it works perfectly. The module has a selection save/restore based on character index within the visible text on a page and is therefore immune to innerHTML changes. You can find the demo here:
http://rangy.googlecode.com/svn/trunk/demos/textrange.html
Documentation (preliminary): http://code.google.com/p/rangy/wiki/TextRangeModule
So basically the code shall be:
document.getElementById("area").onkeyup = function() {
var sel = rangy.getSelection();
var savedSel = sel.saveCharacterRanges(this);
var userInput = this.textContent || this.innerText;
var userInputLength = userInput.length;
var newHTML = [];
for (var i=0; i<userInputLength; i++) {
newHTML[i] = "<span style='color: red'>" + userInput.charAt(i) + "</span>";
}
this.innerHTML = newHTML.join("");
sel.restoreCharacterRanges(this, savedSel);
};
​
Hope this helps.
It looks to me as though it could work. The solution may be as simple as calling the focus() method of the contenteditable <div> before restoring the selection.

Need to be able to add a text to arbitrary location in a div tag as a marker

I have a div tag in my page that could have an arbitrary amount of child nodes. But there is a certain length at which i need to slice it and only show the sliced text. This is the code i have:
var myDiv = document.getElementById("myDiv")
var range = document.body.createTextRange();
range.moveToElementText(myDiv);
range.move("character",150);
range.text = "!!!";
var html = myDiv.innerHTML;
html = html.slice(0,html.indexOf("!!!"));//+"...";
myDiv.innerHTML = html;
I am doing it this way so that i can conserve the html on the value of the div and at the same time i can make sure that i am not slicing in between a tag. This works fine in IE but obviously dosent so in firefox. Can anybody help me with giving me a equivalent code for firefox.
Thanks in advance!
Here's some code to extract the HTML for the first 150 characters of a <div>. It's based on this answer and the same caveats about the naivete of the implementation apply.
Live demo: http://jsfiddle.net/mrEme/2/
Code:
function getTextNodesIn(node) {
var textNodes = [];
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function copyCharacterRange(srcEl, destEl, start, end) {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(srcEl);
var textNodes = getTextNodesIn(srcEl);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount
&& (start < endCharCount ||
(start == endCharCount && i < textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
destEl.appendChild(range.cloneContents());
range.detach();
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(srcEl);
textRange.collapse(true);
textRange.moveEnd("character", end);
textRange.moveStart("character", start);
destEl.innerHTML = textRange.htmlText;
}
}
var srcEl = document.getElementById("src");
var destEl = document.getElementById("dest");
copyCharacterRange(srcEl, destEl, 0, 150);

replace innerHTML in contenteditable div

i need to implement highlight for numbers( in future im add more complex rules ) in the contenteditable div. The problem is When im insert new content with javascript replace, DOM changes and contenteditable div lost focus. What i need is keep focus on div with caret on the current position, so users can just type without any issues and my function simple highlighting numbers. Googling around i decide that Rangy library is the best solution. I have following code:
function formatText() {
var savedSel = rangy.saveSelection();
el = document.getElementById('pad');
el.innerHTML = el.innerHTML.replace(/(<([^>]+)>)/ig,"");
el.innerHTML = el.innerHTML.replace(/([0-9])/ig,"<font color='red'>$1</font>");
rangy.restoreSelection(savedSel);
}
<div contenteditable="true" id="pad" onkeyup="formatText();"></div>
The problem is after function end work focus is coming back to the div, but caret always point at the div begin and i can type anywhere, execept div begin. Also console.log types following Rangy warning: Module SaveRestore: Marker element has been removed. Cannot restore selection.
Please help me to implement this functional. Im open for another solutiona, not only rangy library. Thanks!
http://jsfiddle.net/2rTA5/ This is jsfiddle, but it dont work properly(nothing happens when i typed numbers into my div), dunno maybe it me (first time post code via jsfiddle) or resource doesnt support contenteditable.
UPD* Im read similar problems on stackoverflow, but solutions doesnt suit to my case :(
The problem is that Rangy's save/restore selection module works by inserting invisible marker elements into the DOM where the selection boundaries are and then your code strips out all HTML tags, including Rangy's marker elements (as the error message suggests). You have two options:
Move to a DOM traversal solution for colouring the numbers rather than innerHTML. This will be more reliable but more involved.
Implement an alternative character index-based selection save and restore. This would be generally fragile but will do what you want in this case.
UPDATE
I've knocked up a character index-based selection save/restore for Rangy (option 2 above). It's a little rough, but it does the job for this case. It works by traversing text nodes. I may add this into Rangy in some form. (UPDATE 5 June 2012: I've now implemented this, in a more reliable way, for Rangy.)
jsFiddle: http://jsfiddle.net/2rTA5/2/
Code:
function saveSelection(containerEl) {
var charIndex = 0, start = 0, end = 0, foundStart = false, stop = {};
var sel = rangy.getSelection(), range;
function traverseTextNodes(node, range) {
if (node.nodeType == 3) {
if (!foundStart && node == range.startContainer) {
start = charIndex + range.startOffset;
foundStart = true;
}
if (foundStart && node == range.endContainer) {
end = charIndex + range.endOffset;
throw stop;
}
charIndex += node.length;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i], range);
}
}
}
if (sel.rangeCount) {
try {
traverseTextNodes(containerEl, sel.getRangeAt(0));
} catch (ex) {
if (ex != stop) {
throw ex;
}
}
}
return {
start: start,
end: end
};
}
function restoreSelection(containerEl, savedSel) {
var charIndex = 0, range = rangy.createRange(), foundStart = false, stop = {};
range.collapseToPoint(containerEl, 0);
function traverseTextNodes(node) {
if (node.nodeType == 3) {
var nextCharIndex = charIndex + node.length;
if (!foundStart && savedSel.start >= charIndex && savedSel.start <= nextCharIndex) {
range.setStart(node, savedSel.start - charIndex);
foundStart = true;
}
if (foundStart && savedSel.end >= charIndex && savedSel.end <= nextCharIndex) {
range.setEnd(node, savedSel.end - charIndex);
throw stop;
}
charIndex = nextCharIndex;
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
traverseTextNodes(node.childNodes[i]);
}
}
}
try {
traverseTextNodes(containerEl);
} catch (ex) {
if (ex == stop) {
rangy.getSelection().setSingleRange(range);
} else {
throw ex;
}
}
}
function formatText() {
var el = document.getElementById('pad');
var savedSel = saveSelection(el);
el.innerHTML = el.innerHTML.replace(/(<([^>]+)>)/ig,"");
el.innerHTML = el.innerHTML.replace(/([0-9])/ig,"<font color='red'>$1</font>");
// Restore the original selection
restoreSelection(el, savedSel);
}
I would like to thank Tim for the function he shared here with us, it was very important for a project I'm working on. I embeded his function a small jQuery plugin which can be accessed here: https://jsfiddle.net/sh5tboL8/
$.fn.get_selection_start = function(){
var result = this.get(0).selectionStart;
if (typeof(result) == 'undefined') result = this.get_selection_range().selection_start;
return result;
}
$.fn.get_selection_end = function(){
var result = this.get(0).selectionEnd;
if (typeof(result) == 'undefined') result = this.get_selection_range().selection_end;
return result;
}
$.fn_get_selected_text = function(){
var value = this.get(0).value;
if (typeof(value) == 'undefined'){
var result = this.get_selection_range().selected_text;
}else{
var result = value.substring(this.selectionStart, this.selectionEnd);
}
return result;
}
$.fn.get_selection_range = function(){
var range = window.getSelection().getRangeAt(0);
var cloned_range = range.cloneRange();
cloned_range.selectNodeContents(this.get(0));
cloned_range.setEnd(range.startContainer, range.startOffset);
var selection_start = cloned_range.toString().length;
var selected_text = range.toString();
var selection_end = selection_start + selected_text.length;
var result = {
selection_start: selection_start,
selection_end: selection_end,
selected_text: selected_text
}
return result;
}
$.fn.set_selection = function(selection_start, selection_end){
var target_element = this.get(0);
selection_start = selection_start || 0;
if (typeof(target_element.selectionStart) == 'undefined'){
if (typeof(selection_end) == 'undefined') selection_end = target_element.innerHTML.length;
var character_index = 0;
var range = document.createRange();
range.setStart(target_element, 0);
range.collapse(true);
var node_stack = [target_element];
var node = null;
var start_found = false;
var stop = false;
while (!stop && (node = node_stack.pop())) {
if (node.nodeType == 3){
var next_character_index = character_index + node.length;
if (!start_found && selection_start >= character_index && selection_start <= next_character_index){
range.setStart(node, selection_start - character_index);
start_found = true;
}
if (start_found && selection_end >= character_index && selection_end <= next_character_index){
range.setEnd(node, selection_end - character_index);
stop = true;
}
character_index = next_character_index;
}else{
var child_counter = node.childNodes.length;
while (child_counter --){
node_stack.push(node.childNodes[child_counter]);
}
}
}
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}else{
if (typeof(selection_end) == 'undefined') selection_end = target_element.value.length;
target_element.focus();
target_element.selectionStart = selection_start;
target_element.selectionEnd = selection_end;
}
}
plugin does only what I needed it to do, get selected text, and setting custom text selection. It also works on textboxes and contentEditable divs.

Categories