How would I split a node/element at a position (selection).
Example I have this markup:
<p>This is a te|st, you like?</p>
(this pipe represents the position/selection)
I want to convert it to:
<p>This is a te</p>|<p>st, you like?</p>
Maintaining the selection.
Any ideas?
I and using the Rangy library, and also jQuery, but can use raw JS if applicable.
You could do this by creating a range that extends from the caret to the point immediately after the paragraph and using its extractContents() method.
Live demo: http://jsfiddle.net/timdown/rr9qs/2/
Code:
var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
// Create a copy of the selection range to work with
var range = sel.getRangeAt(0).cloneRange();
// Get the containing paragraph
var p = range.commonAncestorContainer;
while (p && (p.nodeType != 1 || p.tagName != "P") ) {
p = p.parentNode;
}
if (p) {
// Place the end of the range after the paragraph
range.setEndAfter(p);
// Extract the contents of the paragraph after the caret into a fragment
var contentAfterRangeStart = range.extractContents();
// Collapse the range immediately after the paragraph
range.collapseAfter(p);
// Insert the content
range.insertNode(contentAfterRangeStart);
// Move the caret to the insertion point
range.collapseAfter(p);
sel.setSingleRange(range);
}
}
Related
I have an HTML structure like this:
<div contenteditable="true">This is some plain, boring content.</div>
I also have this function that allows me to set the caret position to anywhere I want within the div:
// Move caret to a specific point in a DOM element
function SetCaretPosition(object, pos)
{
// Get key data
var el = object.get(0); // Strip inner object from jQuery object
var range = document.createRange();
var sel = window.getSelection();
// Set the range of the DOM element
range.setStart(el.childNodes[0], pos);
range.collapse(true);
// Set the selection point
sel.removeAllRanges();
sel.addRange(range);
}
This code works completely fine until I start adding child tags (span, b, i, u, strike, sup, sub) to the div e.g.
<div contenteditable="true">
This is some <span class="fancy">plain</span>, boring content.
</div>
Things get more complicated when these child tags end up with child tags of their own e.g.
<div contenteditable="true">
This is some <span class="fancy"><i>plain</i></span>, boring content.
</div>
Essentially, what happens, is that setStart throws an IndexSizeError when I try to SetCaretPosition to an index higher than the start of a child tag. setStart only works until it reaches the first child tag.
What I need, is for the SetCaretPosition function to handle an unknown number of these child tags (and potentially an unknown number of nested child tags) so that setting the position works in the same way it would if there were no tags.
So for both this:
<div contenteditable="true">This is some plain, boring content.</div>
and this:
<div contenteditable="true">
This is <u>some</u> <span class="fancy"><i>plain</i></span>, boring content.
</div>
SetCaretPosition(div, 20); would place the caret before the 'b' in 'boring'.
What is the code I need? Many thanks!
So, I was experiencing the same issue and decided to write my own routine quickly, it walks through all the child nodes recursively and set the position.
Note how this takes a DOM node as argument, not a jquery object as your original post does
// Move caret to a specific point in a DOM element
function SetCaretPosition(el, pos){
// Loop through all child nodes
for(var node of el.childNodes){
if(node.nodeType == 3){ // we have a text node
if(node.length >= pos){
// finally add our range
var range = document.createRange(),
sel = window.getSelection();
range.setStart(node,pos);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
return -1; // we are done
}else{
pos -= node.length;
}
}else{
pos = SetCaretPosition(node,pos);
if(pos == -1){
return -1; // no need to finish the for loop
}
}
}
return pos; // needed because of recursion stuff
}
I hope this'll help you!
If you are going to position the caret based on the character index of the content editable, the easiest way would be using modify method:
const position = 6;
const el = document.querySelector('#editable');
const selection = document.getSelection();
if (!selection || !el) return;
// Set the caret to the beggining
selection.collapse(el, 0);
// Move the caret to the position
for (let index = 0; index < position; index++) {
selection.modify('move', 'forward', 'character');
}
No need to traverse the child nodes.
It only work for object Text childNodes(0).So you have to make it.Here is not so very standard code,but works.Goal is that (p) id of (we) will output object text.If it does then it might work.
<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)
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>
This is specifically for the developers of CKEditor.
The goal is to know when the cursor is either inside or outside a span of custom atttributes.
When using the Ckeditor, if inserted a custom span like below from a plug-in, occassionally when you stop typing, un focus the textarea and replace your cusor to the end of the line - as though you are continuing typing where you had left off. The text can either be inside the span or outside with no encapsulation.
Example before unfocus:
<span style="color:blue;line-height:12px;font-size:10px;font-family:arial;" class="master-span">
<span style="color:red;line-height:20px;font-size:18px;font-family:museo;" class="child-span">Text is here</span>
</span>
Re-Focus and positioning cusor on screen at the end of "here" and start typing.
<span style="color:blue;line-height:12px;font-size:10px;font-family:arial;" class="master-span">
<span style="color:red;line-height:20px;font-size:18px;font-family:museo;" class="child-span">Text is here</span> Text is now outside!!!
</span>
What I'm asking is that where would I target my troubleshoot to know when the cursor/anchor is within the span or outside of it i.e. Is there a calculation being made in the code to determine this?
The reason for this enquiry is that the span formmating is extremely important and we can't use a master span in the surrounding textarea as this can be altered by the user. We find also, that using bulletpoints are troublesome due to the browsers inability to set line-height so ensuring text is always within the span would be a major help.
P.S I've downloaded the source code to see where I could find it.
Many Thanks for any help.
Upon clicking of the text area of any of my CKeditor instances I looked for the parent of the cursor to see if it was an LI node. This indicating that the cursor had landed outside of my span within a bullet point. I proceeded to find the most outside Text Node I could find as my assumption is that if the cursor was outside the span thus the user wanted to continue typing from the last character.
In my setup, within a span there can be a number of multiple sub spans with no limitation of number. So I had to find the most outside span that had a text node at the end (or close to the end).
I did by getting the Node List and reversing the order to find the first text node within the reverse order. I created a function that could loop the number of span and break upon finding the first text node.
Once I had my text node I then set up ranges and calculated the length of the text in order to place it at the end. Below is my final solution which works on latest Chrome/FF/IE.
$("#preview-text-3827").on("click", function(){
var CKEDITOR = window.parent.CKEDITOR;
var ck_instance_name = false;
for ( var ck_instance in CKEDITOR.instances ){
if (CKEDITOR.instances[ck_instance].focusManager.hasFocus){
ck_instance_name = ck_instance;
break;
}
}
var editor = CKEDITOR.instances[ck_instance_name];
var selection = editor.getSelection();
var parent_attrs = "";
if (selection.getType() == CKEDITOR.SELECTION_TEXT) {
parent_attrs = selection.getStartElement();
if(parent_attrs.getName() == "li"){
var nodeList = parent_attrs.getChildren();
console.log( "Now Reverse" );
for ( var i = nodeList.count() - 1; i > -1; --i ) {
//console.log( nodeList.getItem( i).nodeName );
var el = nodeList.getItem( i);
if(el.$.nodeName == "#text"){
// This is the last text but it's inside the li which is WRONG
}
if(el.$.nodeName == "SPAN"){
// This should be the last span
// Jump into this span and find the children.
var result = retractLiPosition(el);
if(result.text == true){
var inner = result.result;
var text = inner.$.textContent || inner.$.innerText;
var length = text.length;
var range = editor.createRange();
range.setStart( inner , length);
range.setEnd( inner, length);
editor.getSelection().selectRanges( [ range ] );
break;
}
}
}
}
}
});
function retractLiPosition(element){
var returning = new Object();
returning.result = element;
returning.text = false;
var result = element;
var nodeList = element.getChildren();
for ( var i = nodeList.count() - 1; i > -1; --i ) {
var el = nodeList.getItem( i);
if(el.$.nodeName == "#text"){
returning.result = el;
returning.text = true;
break;
}
if(el.$.nodeName == "SPAN"){
// This should be the last span
// Jump into this span and find the children.
returning = retractLiPosition(el);
}
}
return returning;
}
});
With the exception of using Undo, I don't think there's a way to remove h1 and h2 tags in content editable. The expected behavior is clicking the H1 button again should toggle it off, but it does not. There's also a "remove formatting" button, but it only works on items that are bold, italic, etc. Is there a way to do this through javascript?
Edit: Result must remove the opening and closing H1 tag, and not replace it with anything else.
Please see the simplified test case here:
http://jsfiddle.net/kthornbloom/GSnbb/1/
<div id="editor" contenteditable="true">
<h1>This is a heading one</h1>
How can I remove the header styling if I want to?
</div>
I decided to implement the approach I outlined in my comment to my other answer: traversing nodes within the selected range and removing particular nodes (in this case, based on tag name).
Here's the full demo. It won't work in IE <= 8 (which lacks DOM Range and Selection support) but will in everything other major current browser. One problem is that the selection isn't always preserved, but that isn't too hard to achieve.
http://jsfiddle.net/gF3sa/1/
This example includes modified range traversal code from elsewhere on SO.
function nextNode(node) {
if (node.hasChildNodes()) {
return node.firstChild;
} else {
while (node && !node.nextSibling) {
node = node.parentNode;
}
if (!node) {
return null;
}
return node.nextSibling;
}
}
function getRangeSelectedNodes(range, includePartiallySelectedContainers) {
var node = range.startContainer;
var endNode = range.endContainer;
var rangeNodes = [];
// Special case for a range that is contained within a single node
if (node == endNode) {
rangeNodes = [node];
} else {
// Iterate nodes until we hit the end container
while (node && node != endNode) {
rangeNodes.push( node = nextNode(node) );
}
// Add partially selected nodes at the start of the range
node = range.startContainer;
while (node && node != range.commonAncestorContainer) {
rangeNodes.unshift(node);
node = node.parentNode;
}
}
// Add ancestors of the range container, if required
if (includePartiallySelectedContainers) {
node = range.commonAncestorContainer;
while (node) {
rangeNodes.push(node);
node = node.parentNode;
}
}
return rangeNodes;
}
function getSelectedNodes() {
var nodes = [];
if (window.getSelection) {
var sel = window.getSelection();
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
nodes.push.apply(nodes, getRangeSelectedNodes(sel.getRangeAt(i), true));
}
}
return nodes;
}
function replaceWithOwnChildren(el) {
var parent = el.parentNode;
while (el.hasChildNodes()) {
parent.insertBefore(el.firstChild, el);
}
parent.removeChild(el);
}
function removeSelectedElements(tagNames) {
var tagNamesArray = tagNames.toLowerCase().split(",");
getSelectedNodes().forEach(function(node) {
if (node.nodeType == 1 &&
tagNamesArray.indexOf(node.tagName.toLowerCase()) > -1) {
// Remove the node and replace it with its children
replaceWithOwnChildren(node);
}
});
}
removeSelectedElements("h1,h2,h3,h4,h5,h6");
This may not exactly meet your needs, but you could do it by using the FormatBlock command and passing in "div" or "pre" as the final parameter:
document.execCommand('formatBlock', false, 'p');
Demo: http://jsfiddle.net/GSnbb/2/ [jsFiddle has been deleted]
EDIT: Yes, this doesn't answer the question as it is now. However, it pre-dates the edit to the question about not replacing the <h1> element and was a reasonable answer to the original question.
It is feasible with javascript, logic is the following:
get the selected text and its position (cf.
Get the Highlighted/Selected text
and
javascript - Getting selected text position)
remove all the <h1> and </h1> from the selected text
s = s.replace(/<h1>/g, '');
s = s.replace(/<\/h1>/g,'');
Insert the corrected text in place of the original one
I have drafted a solution based on your JSFiddle, but it requires some tweaking.
works: removing <h1> and </h1> from selected text on Gecko and webKit based browsers
not developed: IE support - cf. links in the jsfiddle, should not be difficult
broken:
replacement of incomplete selections (containing only one of <h1> and </h1>) - easy to fix
removal of <h1> when it is right at the beginning of the selected text - you will need to play around a bit more with selections and ranges to sort that out.
P.S. Have you considered using an existing text editor plugin instead of creating it by yourself ?
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.
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.