Custom select function with copy to clipboard pure JS - javascript

The current code appends a button to quickly select some code in a <pre> tag. What I want to add is the ability to copy that content to the clipboard and change the button text to "copied".
How can I achieve it by modifying the current working code below? I wouldn't mind using clipboard.js, jQuery bits or just native JS support as it was introduced since Chrome 43. I just dont know how to go on from here on adding what I need.
function selectPre(e) {
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
else {
var r = document.createRange();
r.setStart(e.firstChild, 0);
r.setEnd(e.lastChild, e.lastChild.textContent.length);
s.removeAllRanges();
s.addRange(r);
}
}
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
else if (document.selection) {
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
var newdiff = diff[i].childNodes[1];
if (newdiff.className && (newdiff.className == 'added' || newdiff.className == 'modified')) {
newdiff.className += ' diff-select';
newdiff.innerHTML = '<div class="btnbox"><button class="btn btn-default btn-xs" onclick="selectPre(this.parentNode.nextSibling)">Select</button></div>' + newdiff.innerHTML;
}
}

For some reason indeed your selectPre function is not found when reproducing the case on jsfiddle. Jsfiddle may get rid of what it thinks is dead code or rename it for the sake of minification.
But if what it does is selecting the content of a <pre> tag, the clipboard.js library (that you are ready to use) can do that already on its own.
So you end up by requiring a correct configuration of the Clipboard object. Using that one:
new Clipboard('.btn', {
// The targeting to the correct content is done here.
target: function(trigger) {
return trigger.parentNode.nextSibling;
}
// clipboard.js will take the entire inner content of the <pre>,
// I think this is what you are trying to do in your "selectPre"
// function, but I am not sure.
});
it mimics your selectPre(this.parentNode.nextSibling) that you no longer need to attach to the onclick attribute of your button.
Demo: http://jsfiddle.net/5k60nm1y/
Note that I had to guess what your table structure is. It might differ from your actual table so you may need to fine-tune how newdiff is assigned to the correct cell.
If you need something more complicated than just the inner content of the <pre> tag, you could fine-tune the behaviour of the Clipboard object by passing a custom function to the text property of the Clipboard constructor option, instead of using the target property. Check the clipboard homepage, it is quite self-explanatory.
As mentioned by Zac, you would have made people's task easier (and you would probably have received a solution much faster) if you could have shared your HTML table. I would not have needed to guess and create a fake one. Furthermore, the code I would have provided you with would have been directly applicable to your real table, whereas now it may still need customization. Hopefully I guessed it right enough and my table is close to yours.

I applied a piece of code from this resource, How do I copy to the clipboard in JavaScript?, to your code, for you to easily see how it can be done.
I also modified your onclick="selectPre(...)" to this onclick="selectPre(this)" and added a couple of variables in the "selectPre" function.
Here is also a Fiddle demo
function selectPre(b) {
var s; // added - selection variable
var e = b.parentNode.nextSibling; // added - parent sibling element
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
else {
var r = document.createRange();
r.setStart(e.firstChild, 0);
r.setEnd(e.lastChild, e.lastChild.textContent.length);
s.removeAllRanges();
s.addRange(r);
}
}
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
else if (document.selection) {
var s = document.body.createTextRange();
s.moveToElementText(e);
s.select();
}
// added - copy and change button text
if (s) {
try {
var successful = document.execCommand('copy');
// var msg = successful ? 'successful' : 'unsuccessful';
// console.log('Copying text command was ' + msg);
if (successful) {
b.innerHTML = "Copied";
}
} catch (err) {
// console.log('Oops, unable to copy');
}
}
}
var diff = document.getElementById('diff_table').getElementsByTagName('tr');
var difflen = diff.length;
for(i=0; i<difflen; i++) {
var newdiff = diff[i].childNodes[1];
if (newdiff.className && (newdiff.className == 'added' || newdiff.className == 'modified')) {
newdiff.className += ' diff-select';
// altered - onclick handler
newdiff.innerHTML = '<div class="btnbox"><button class="btn btn-default btn-xs" onclick="selectPre(this)">Select</button></div>' + newdiff.innerHTML;
}
}

Related

Any way to prevent losing focus when clicking an input text out of tinymce container?

I've made this tinymce fiddle to show what I say.
Highlight text in the editor, then click on the input text, highlight in tinyMCE is lost (obviously).
Now, I know it's not easy since both, the inline editor and the input text are in the same document, thus, the focus is only one. But is there any tinymce way to get like an "unfocused" highlight (gray color) whenever I click in an input text?
I'm saying this because I have a customized color picker, this color picker has an input where you can type in the HEX value, when clicking OK it would execCommand a color change on the selected text, but it looks ugly because the highlight is lost.
I don't want to use an iframe, I know that by using the non-inline editor (iframe) is one of the solutions, but for a few reasons, i can't use an iframe text editor.
Any suggestion here? Thanks.
P.S: Out of topic, does any of you guys know why I can't access to tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global var was overwritten by the tinymce select dom element of the page itself. I can't execute a tinyMCE command lol.
Another solution:
http://fiddle.tinymce.com/sBeaab/5
P.S: Out of topic, does any of you guys know why I can't access to
tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global
var was overwritten by the tinymce select dom element of the page
itself. I can't execute a tinyMCE command lol.
Well, you can access the tinyMCE variable and even execute commands.
this line is wrong
var colorHex = document.getElementById("colorHex")
colorHex contains input element, not value.
var colorHex = document.getElementById("colorHex").value
now it works ( neolist couldn't load, so I removed it )
http://fiddle.tinymce.com/DBeaab/1
I had to do something similar recently.
First off, you can't really have two different elements "selected" simultaneously. So in order to accomplish this you're going to need to mimic the browser's built-in 'selected text highlight'. To do this, you're going to have to insert spans into the text to simulate highlighting, and then capture the mousedown and mouseup events.
Here's a fiddle from StackOverflow user "fullpipe" which illustrates the technique I used.
http://jsfiddle.net/fullpipe/DpP7w/light/
$(document).ready(function() {
var keylist = "abcdefghijklmnopqrstuvwxyz123456789";
function randWord(length) {
var temp = '';
for (var i=0; i < length; i++)
temp += keylist.charAt(Math.floor(Math.random()*keylist.length));
return temp;
}
for(var i = 0; i < 500; i++) {
var len = Math.round(Math.random() * 5 + 3);
document.body.innerHTML += '<span id="'+ i +'">' + randWord(len) + '</span> ';
}
var start = null;
var end = null;
$('body').on('mousedown', function(event) {
start = null;
end = null;
$('span.s').removeClass('s');
start = $(event.target);
start.addClass('s');
});
$('body').on('mouseup', function(event) {
end = $(event.target);
end.addClass('s');
if(start && end) {
var between = getAllBetween(start,end);
for(var i=0, len=between.length; i<len;i++)
between[i].addClass('s');
alert('You select ' + (len) + ' words');
}
});
});
function getAllBetween(firstEl,lastEl) {
var firstIdx = $('span').index($(firstEl));
var lastIdx = $('span').index($(lastEl));
if(lastIdx == firstIdx)
return [$(firstEl)];
if(lastIdx > firstIdx) {
var firstElement = $(firstEl);
var lastElement = $(lastEl);
} else {
var lastElement = $(firstEl);
var firstElement = $(lastEl);
}
var collection = new Array();
collection.push(firstElement);
firstElement.nextAll().each(function(){
var siblingID = $(this).attr("id");
if (siblingID != $(lastElement).attr("id")) {
collection.push($(this));
} else {
return false;
}
});
collection.push(lastElement);
return collection;
}
As you can see in the fiddle, the gibberish text in the right pane stays highlighted regardless of focus elsewhere on the page.
At that point, you're going to have to apply your color changes to all matching spans.

Create multiple selection at the same time when using document.selection in Javascript

I've known how to use the document.selection to do the highlighting. For example
/* http://jsfiddle.net/4J2dy/ */
$("#content").on('mouseup', function() {
highlighting();
});
var highlighting = function () {
var seleted_str = (document.all) ? document.selection.createRange().text : document.getSelection();
if(seleted_str != "") {
var stringToBeHighlighted = seleted_str.getRangeAt(0);
var span = document.createElement("span");
span.style.cssText = "background-color: #80deea";
span.className = "MT";
stringToBeHighlighted.surroundContents(span);
}
};
But there is something I don't know how to achieve.
Let's say that I have four layers created with the same content at the same time.
And I would like to select a sentence on the controlling layer while all the same sentence in the other three layers will be selected too.(See image below)
After the selection, I would like to pop out a menu(which I can do), and get the DOM element based on which button is pressed.(See image below)
Could anyone tell me how to achieve this? Or it just can't be done? I would be grateful if someone could answer for me.
It's kind of possible, and I would appreciate the input of SO user Tim Down as he knows a lot about JS Range/Selections, but I'll present my partial solution already.
Instead of selecting the 4 layers, you could just store the startOffset & endOffset in an external object that is updated on mouseup. The only by-effect this has, is that the user's selection will only get the color of the span when they click a layer button.
The advantage is that you can now simply work with DOM Textnodes as opposed to ranges/ selection (more complex, to me anyway).
I've chosen to find the layers with a data-layer attribute on the buttons and a corresponding id on the layers themselves. I handled the 'appending' of the 'selected span' by slicing the text content of the text nodes in the layers, like so:
layer.innerHTML = txt.slice(0, selText.start)
+ '<span class="MT" style="background-color: #80deea">'
+ txt.slice(selText.start, selText.end) + '</span>'
+ txt.slice(selText.end, txt.length);
See it in action here. I've added a cleanSelection function so only one selection is possible at a time (the start & end counters fail because selection ranges don't take into account HTML tags, so you have to get rid of the spans).
Final notes:
The fiddle will not work in browsers not supporting getElementsByClassName
The fiddle only supports one selection at a time.
The fiddle does not extensively test all conditions (eg, whether the nodetype of the first child is truly a text node, etc. But it ain't hard to add that yourself)
Entire JS code as reference (also in fiddle):
// this object will hold the start & end offsets of selection value
var selText = false;
// selText will be updated on mouseup
document.body.onmouseup = getSelText;
// on button click, selText will be highlighted
document.body.onclick = function(e) {
var target = e.target || e.srcElement, range, layer, txt;
// only do if it's a layer button & the selection is non-empty
if (target.getAttribute('data-layer') && selText !== false) {
// first remove previous spans, they break the startOffset & endOffset of the selection range
cleanSelection();
// get the clicked layer
layer = document.getElementById(target.getAttribute('data-layer'));
// this assumes that the first node in the layer is a textNode
txt = layer.firstChild.nodeValue;
// let's append the selection container now
layer.innerHTML = txt.slice(0, selText.start)
+ '<span class="MT" style="background-color: #80deea">'
+ txt.slice(selText.start, selText.end) + '</span>'
+ txt.slice(selText.end, txt.length);
// ...and empty the 'real selection'
window.getSelection().collapse();
// log results to console
console.log('From char ' + selText.start + ' to char ' + selText.end + ', in ' + layer.id);
}
};
function getSelText () {
var seleted_str = (document.all) ? document.selection.createRange().text : document.getSelection(), stringToBeHighlighted;
if(seleted_str !== "") {
stringToBeHighlighted = seleted_str.getRangeAt(0);
selText = {
start: stringToBeHighlighted.startOffset,
end: stringToBeHighlighted.endOffset
};
} else {
selText = false;
}
}
function cleanSelection() {
var getText, mtSpan = document.getElementsByClassName('MT');
for ( var i = 0; i < mtSpan.length; i++) {
getText = mtSpan[i].innerHTML;
mtSpan[i].previousSibling.nodeValue = mtSpan[i].previousSibling.nodeValue + getText + mtSpan[i].nextSibling.nodeValue;
mtSpan[i].parentNode.removeChild(mtSpan[i].nextSibling);
mtSpan[i].parentNode.removeChild(mtSpan[i]);
}
}

How can I use JavaScript to select text in a pre node/block?

I understand the security reasons behind dis-allowing JS copying arbitrary text to the clipboard, but is there a method by which clicking a button can select the text in a pre node similar to how the select() function works in an input?
I am not looking for the jQuery plugin that copies to clipboard. I just want to text in pre block to be highlighted so user can ctrl-c to copy.
I seem to finding squat.
This is what you need:
var clip = function(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
};
And the html:
<pre onclick="clip(this);" id="copy_paste"></pre>
Or if you want to programmatically do this:
clip(document.getElementById("copy_paste"));
Or in jquery:
clip($("#copy_paste")[0]);
You cannot pass the jquery element clip() as argument el. It will give "TypeError: Argument 1 of Range.selectNodeContents does not implement interface Node."
It's not too hard. You need separate branches for IE < 9 and all other browsers. Here's a function to select the contents of an element:
Live demo: http://jsfiddle.net/yQa2w/
Code:
function selectElementContents(el) {
if (window.getSelection && document.createRange) {
// IE 9 and non-IE
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.body.createTextRange) {
// IE < 9
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.select();
}
}
Maybe you could change the pre tag into a textarea tag when the user clicks on it:
jsFiddle: http://jsfiddle.net/WzBQf/
<button id="btnSelect">Select!</button>
<button id="btnDeselect">Deselect!</button>
<hr />
<div id="text">
<pre id="txt1">Test</pre>
<textarea id="txt2" readonly="readonly"></textare>
</div>
And the JavaScript (jQuery) code:
$("#txt1, #btnSelect").click(function() {
Select();
});
function Select() {
$("#txt2").val($("#txt1").html()).show();
$("#txt1").hide();
$("#txt2").focus()[0].select();
}
function Deselect() {
$("#txt1").html($("#txt2").val()).show();
$("#txt2").hide();
}
$("#txt2").blur(function() {
Deselect();
});
$("#btnDeselect").click(function() {
Deselect();
});
take a look at
https://developer.mozilla.org/it/DOM/window.getSelection
it is not compatible with all mayor browsers, first IE implementation is in version 9
but in older IEs there is some alternative API in document.selection, that seems equivalent
http://msdn.microsoft.com/en-us/library/ms535869%28v=vs.85%29.aspx
good luck!
As far as I know, you can not select text outside <input> or <textarea>. Btw, why do you need that?
OK - this is what I am doing based on jsFiddle's suggestion and it works. Only problem is I do not have Windows and in IE where I do have it copy to clipboard, apparently the line breaks are broken, but that's not this question (and I suspect a .replace() can fix it - I just need access to windows to play with IE):
function lineBreakCount(str){
// http://snippets.dzone.com/posts/show/5770
/* counts \n */
try {
return((str.match(/[^\n]*\n[^\n]*/gi).length));
} catch(e) {
return 0;
}
}
function nodeToCopy($node) {
// For Code Snippets - [AW]
$pre = $node.find('pre:first');
var string = $pre.text();
if (window.clipboardData && clipboardData.setData) {
clipboardData.setData('text', string);
} else {
var n = 1 + lineBreakCount(string);
$pre.attr('class','nodisplay');
$pre.after('<textarea readonly="readonly" rows="' + n + '" class="dbg-copycode">' + string.replace(/</g,'<').replace(/>/,'>') + '</textarea>');
$node.find('textarea:first').focus();
$node.find('textarea:first').select();
$node.find('div:last').find('button').replaceWith('<button class="dbg-copycode" type="button" title="Restore syntax highlight">Restore</button>');
$node.find('div:last').find('button').click(function() {restorePreFromText($(this).parent().parent())});
}
}
function restorePreFromText($node) {
// For Code Snippets - [AW]
$node.find('pre:first').removeAttr('class');
$node.find('textarea').remove();
$node.find('div:last').find('button').replaceWith('<button class="dbg-copycode" type="button" title="Select code example for copying">Select Code</button>');
$node.find('div:last').find('button').click(function() {nodeToCopy($(this).parent().parent())});
}
$(document).ready(function() {
// For Code Snippets - [AW]
var copybutton = 'Select Code';
var copytitle = 'Select code example for copying';
if (window.clipboardData && clipboardData.setData) {
copybutton = 'Copy Code';
copytitle = 'Copy code example to clipboard';
}
$('pre[data-code]').after('<div class="dbg-rbutton"><button class="dbg-copycode" type="button" title="' + copytitle + '">' + copybutton + '</button></div>');
$('.dbg-copycode').click(function() {nodeToCopy($(this).parent().parent())});
});
The reason I'm not using .hide() where I hide the pre block is because .hide() adds a style attribute which is forbidden under the Mozilla CSP policy the server uses, so I have to set a class attribute instead.

javascript catch paste event in textarea

I currently have a textarea which I requires control over text that has been pasted in,
essentially I need to be able to take whatever the user wants to paste into a textarea and place it into a variable.
I will then work out the position in which they pasted the text and the size of the string to remove it from the textarea,
Then at the end deal with the text thats is in the variable in my own way.
My question: how would I go about getting a copy of the text in a variable that was just pasted in by the user?
Thanks.
I answered a similar question a few days ago: Detect pasted text with ctrl+v or right click -> paste. This time I've included quite a long function that accurately gets selection boundaries in textarea in IE; the rest is relatively simple.
You can use the paste event to detect the paste in most browsers (notably not Firefox 2 though). When you handle the paste event, record the current selection, and then set a brief timer that calls a function after the paste has completed. This function can then compare lengths to know where to look for the pasted content. Something like the following:
function getSelectionBoundary(el, start) {
var property = start ? "selectionStart" : "selectionEnd";
var originalValue, textInputRange, precedingRange, pos, bookmark, isAtEnd;
if (typeof el[property] == "number") {
return el[property];
} else if (document.selection && document.selection.createRange) {
el.focus();
var range = document.selection.createRange();
if (range) {
// Collapse the selected range if the selection is not a caret
if (document.selection.type == "Text") {
range.collapse(!!start);
}
originalValue = el.value;
textInputRange = el.createTextRange();
precedingRange = el.createTextRange();
pos = 0;
bookmark = range.getBookmark();
textInputRange.moveToBookmark(bookmark);
if (/[\r\n]/.test(originalValue)) {
// Trickier case where input value contains line breaks
// Test whether the selection range is at the end of the
// text input by moving it on by one character and
// checking if it's still within the text input.
try {
range.move("character", 1);
isAtEnd = (range.parentElement() != el);
} catch (ex) {
log.warn("Error moving range", ex);
isAtEnd = true;
}
range.moveToBookmark(bookmark);
if (isAtEnd) {
pos = originalValue.length;
} else {
// Insert a character in the text input range and use
// that as a marker
textInputRange.text = " ";
precedingRange.setEndPoint("EndToStart", textInputRange);
pos = precedingRange.text.length - 1;
// Delete the inserted character
textInputRange.moveStart("character", -1);
textInputRange.text = "";
}
} else {
// Easier case where input value contains no line breaks
precedingRange.setEndPoint("EndToStart", textInputRange);
pos = precedingRange.text.length;
}
return pos;
}
}
return 0;
}
function getTextAreaSelection(textarea) {
var start = getSelectionBoundary(textarea, true),
end = getSelectionBoundary(textarea, false);
return {
start: start,
end: end,
length: end - start,
text: textarea.value.slice(start, end)
};
}
function detectPaste(textarea, callback) {
textarea.onpaste = function() {
var sel = getTextAreaSelection(textarea);
var initialLength = textarea.value.length;
window.setTimeout(function() {
var val = textarea.value;
var pastedTextLength = val.length - (initialLength - sel.length);
var end = sel.start + pastedTextLength;
callback({
start: sel.start,
end: end,
length: pastedTextLength,
text: val.slice(sel.start, end),
replacedText: sel.text
});
}, 1);
};
}
window.onload = function() {
var textarea = document.getElementById("your_textarea");
detectPaste(textarea, function(pasteInfo) {
var val = textarea.value;
// Delete the pasted text and restore any previously selected text
textarea.value = val.slice(0, pasteInfo.start) +
pasteInfo.replacedText + val.slice(pasteInfo.end);
alert(pasteInfo.text);
});
};
You might now use FilteredPaste.js (http://willemmulder.github.com/FilteredPaste.js/) instead. It will let you control what content gets pasted into a textarea or contenteditable and you will be able to filter/change/extract content at will.
A quick search shows me that there are different methods for different browsers. I'm not sure if jQuery has a solution. Prototype.js does not appear to have one. Maybe YUI can do this for you?
You can also use TinyMCE, since it does have a gazillion of different event triggers. It is a full fledged word processor, but you can use it as plain text if you want. It might be a bit too much weight to add though. For example, upon initiation, it turns your <textarea> into an iFrame with several sub. But it will do what you ask.
--Dave

Set cursor position on contentEditable <div>

I am after a definitive, cross-browser solution to set the cursor/caret position to the last known position when a contentEditable='on' <div> regains focus. It appears default functionality of a content editable div is to move the caret/cursor to the beginning of the text in the div each time you click on it, which is undesirable.
I believe I would have to store in a variable the current cursor position when they are leaving focus of the div, and then re-set this when they have focus inside again, but I have not been able to put together, or find a working code sample yet.
If anybody has any thoughts, working code snippets or samples I'd be happy to see them.
I don't really have any code yet but here is what I do have:
<script type="text/javascript">
// jQuery
$(document).ready(function() {
$('#area').focus(function() { .. } // focus I would imagine I need.
}
</script>
<div id="area" contentEditable="true"></div>
PS. I have tried this resource but it appears it does not work for a <div>. Perhaps only for textarea (How to move cursor to end of contenteditable entity)
This solution works in all major browsers:
saveSelection() is attached to the onmouseup and onkeyup events of the div and saves the selection to the variable savedRange.
restoreSelection() is attached to the onfocus event of the div and reselects the selection saved in savedRange.
This works perfectly unless you want the selection to be restored when the user clicks the div aswell (which is a bit unintuitative as normally you expect the cursor to go where you click but code included for completeness)
To achieve this the onclick and onmousedown events are canceled by the function cancelEvent() which is a cross browser function to cancel the event. The cancelEvent() function also runs the restoreSelection() function because as the click event is cancelled the div doesn't receive focus and therefore nothing is selected at all unless this functions is run.
The variable isInFocus stores whether it is in focus and is changed to "false" onblur and "true" onfocus. This allows click events to be cancelled only if the div is not in focus (otherwise you would not be able to change the selection at all).
If you wish to the selection to be change when the div is focused by a click, and not restore the selection onclick (and only when focus is given to the element programtically using document.getElementById("area").focus(); or similar then simply remove the onclick and onmousedown events. The onblur event and the onDivBlur() and cancelEvent() functions can also safely be removed in these circumstances.
This code should work if dropped directly into the body of an html page if you want to test it quickly:
<div id="area" style="width:300px;height:300px;" onblur="onDivBlur();" onmousedown="return cancelEvent(event);" onclick="return cancelEvent(event);" contentEditable="true" onmouseup="saveSelection();" onkeyup="saveSelection();" onfocus="restoreSelection();"></div>
<script type="text/javascript">
var savedRange,isInFocus;
function saveSelection()
{
if(window.getSelection)//non IE Browsers
{
savedRange = window.getSelection().getRangeAt(0);
}
else if(document.selection)//IE
{
savedRange = document.selection.createRange();
}
}
function restoreSelection()
{
isInFocus = true;
document.getElementById("area").focus();
if (savedRange != null) {
if (window.getSelection)//non IE and there is already a selection
{
var s = window.getSelection();
if (s.rangeCount > 0)
s.removeAllRanges();
s.addRange(savedRange);
}
else if (document.createRange)//non IE and no selection
{
window.getSelection().addRange(savedRange);
}
else if (document.selection)//IE
{
savedRange.select();
}
}
}
//this part onwards is only needed if you want to restore selection onclick
var isInFocus = false;
function onDivBlur()
{
isInFocus = false;
}
function cancelEvent(e)
{
if (isInFocus == false && savedRange != null) {
if (e && e.preventDefault) {
//alert("FF");
e.stopPropagation(); // DOM style (return false doesn't always work in FF)
e.preventDefault();
}
else {
window.event.cancelBubble = true;//IE stopPropagation
}
restoreSelection();
return false; // false = IE style
}
}
</script>
This is compatible with the standards-based browsers, but will probably fail in IE. I'm providing it as a starting point. IE doesn't support DOM Range.
var editable = document.getElementById('editable'),
selection, range;
// Populates selection and range variables
var captureSelection = function(e) {
// Don't capture selection outside editable region
var isOrContainsAnchor = false,
isOrContainsFocus = false,
sel = window.getSelection(),
parentAnchor = sel.anchorNode,
parentFocus = sel.focusNode;
while(parentAnchor && parentAnchor != document.documentElement) {
if(parentAnchor == editable) {
isOrContainsAnchor = true;
}
parentAnchor = parentAnchor.parentNode;
}
while(parentFocus && parentFocus != document.documentElement) {
if(parentFocus == editable) {
isOrContainsFocus = true;
}
parentFocus = parentFocus.parentNode;
}
if(!isOrContainsAnchor || !isOrContainsFocus) {
return;
}
selection = window.getSelection();
// Get range (standards)
if(selection.getRangeAt !== undefined) {
range = selection.getRangeAt(0);
// Get range (Safari 2)
} else if(
document.createRange &&
selection.anchorNode &&
selection.anchorOffset &&
selection.focusNode &&
selection.focusOffset
) {
range = document.createRange();
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
} else {
// Failure here, not handled by the rest of the script.
// Probably IE or some older browser
}
};
// Recalculate selection while typing
editable.onkeyup = captureSelection;
// Recalculate selection after clicking/drag-selecting
editable.onmousedown = function(e) {
editable.className = editable.className + ' selecting';
};
document.onmouseup = function(e) {
if(editable.className.match(/\sselecting(\s|$)/)) {
editable.className = editable.className.replace(/ selecting(\s|$)/, '');
captureSelection();
}
};
editable.onblur = function(e) {
var cursorStart = document.createElement('span'),
collapsed = !!range.collapsed;
cursorStart.id = 'cursorStart';
cursorStart.appendChild(document.createTextNode('—'));
// Insert beginning cursor marker
range.insertNode(cursorStart);
// Insert end cursor marker if any text is selected
if(!collapsed) {
var cursorEnd = document.createElement('span');
cursorEnd.id = 'cursorEnd';
range.collapse();
range.insertNode(cursorEnd);
}
};
// Add callbacks to afterFocus to be called after cursor is replaced
// if you like, this would be useful for styling buttons and so on
var afterFocus = [];
editable.onfocus = function(e) {
// Slight delay will avoid the initial selection
// (at start or of contents depending on browser) being mistaken
setTimeout(function() {
var cursorStart = document.getElementById('cursorStart'),
cursorEnd = document.getElementById('cursorEnd');
// Don't do anything if user is creating a new selection
if(editable.className.match(/\sselecting(\s|$)/)) {
if(cursorStart) {
cursorStart.parentNode.removeChild(cursorStart);
}
if(cursorEnd) {
cursorEnd.parentNode.removeChild(cursorEnd);
}
} else if(cursorStart) {
captureSelection();
var range = document.createRange();
if(cursorEnd) {
range.setStartAfter(cursorStart);
range.setEndBefore(cursorEnd);
// Delete cursor markers
cursorStart.parentNode.removeChild(cursorStart);
cursorEnd.parentNode.removeChild(cursorEnd);
// Select range
selection.removeAllRanges();
selection.addRange(range);
} else {
range.selectNode(cursorStart);
// Select range
selection.removeAllRanges();
selection.addRange(range);
// Delete cursor marker
document.execCommand('delete', false, null);
}
}
// Call callbacks here
for(var i = 0; i < afterFocus.length; i++) {
afterFocus[i]();
}
afterFocus = [];
// Register selection again
captureSelection();
}, 10);
};
Update
I've written a cross-browser range and selection library called Rangy that incorporates an improved version of the code I posted below. You can use the selection save and restore module for this particular question, although I'd be tempted to use something like #Nico Burns's answer if you're not doing anything else with selections in your project and don't need the bulk of a library.
Previous answer
You can use IERange (http://code.google.com/p/ierange/) to convert IE's TextRange into something like a DOM Range and use it in conjunction with something like eyelidlessness's starting point. Personally I would only use the algorithms from IERange that do the Range <-> TextRange conversions rather than use the whole thing. And IE's selection object doesn't have the focusNode and anchorNode properties but you should be able to just use the Range/TextRange obtained from the selection instead.
I might put something together to do this, will post back here if and when I do.
EDIT:
I've created a demo of a script that does this. It works in everything I've tried it in so far except for a bug in Opera 9, which I haven't had time to look into yet. Browsers it works in are IE 5.5, 6 and 7, Chrome 2, Firefox 2, 3 and 3.5, and Safari 4, all on Windows.
http://www.timdown.co.uk/code/selections/
Note that selections may be made backwards in browsers so that the focus node is at the start of the selection and hitting the right or left cursor key will move the caret to a position relative to the start of the selection. I don't think it is possible to replicate this when restoring a selection, so the focus node is always at the end of the selection.
I will write this up fully at some point soon.
I had a related situation, where I specifically needed to set the cursor position to the END of a contenteditable div. I didn't want to use a full fledged library like Rangy, and many solutions were far too heavyweight.
In the end, I came up with this simple jQuery function to set the carat position to the end of a contenteditable div:
$.fn.focusEnd = function() {
$(this).focus();
var tmp = $('<span />').appendTo($(this)),
node = tmp.get(0),
range = null,
sel = null;
if (document.selection) {
range = document.body.createTextRange();
range.moveToElementText(node);
range.select();
} else if (window.getSelection) {
range = document.createRange();
range.selectNode(node);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
tmp.remove();
return this;
}
The theory is simple: append a span to the end of the editable, select it, and then remove the span - leaving us with a cursor at the end of the div. You could adapt this solution to insert the span wherever you want, thus putting the cursor at a specific spot.
Usage is simple:
$('#editable').focusEnd();
That's it!
I took Nico Burns's answer and made it using jQuery:
Generic: For every div contentEditable="true"
Shorter
You'll need jQuery 1.6 or higher:
savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
var s = window.getSelection();
var t = $('div[contenteditable="true"]').index(this);
if (typeof(savedRanges[t]) === "undefined"){
savedRanges[t]= new Range();
} else if(s.rangeCount > 0) {
s.removeAllRanges();
s.addRange(savedRanges[t]);
}
}).bind("mouseup keyup",function(){
var t = $('div[contenteditable="true"]').index(this);
savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
if(!$(this).is(":focus")){
e.stopPropagation();
e.preventDefault();
$(this).focus();
}
});
savedRanges = new Object();
$('div[contenteditable="true"]').focus(function(){
var s = window.getSelection();
var t = $('div[contenteditable="true"]').index(this);
if (typeof(savedRanges[t]) === "undefined"){
savedRanges[t]= new Range();
} else if(s.rangeCount > 0) {
s.removeAllRanges();
s.addRange(savedRanges[t]);
}
}).bind("mouseup keyup",function(){
var t = $('div[contenteditable="true"]').index(this);
savedRanges[t] = window.getSelection().getRangeAt(0);
}).on("mousedown click",function(e){
if(!$(this).is(":focus")){
e.stopPropagation();
e.preventDefault();
$(this).focus();
}
});
div[contenteditable] {
padding: 1em;
font-family: Arial;
outline: 1px solid rgba(0,0,0,0.5);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
<div contentEditable="true"></div>
After playing around I've modified eyelidlessness' answer above and made it a jQuery plugin so you can just do one of these:
var html = "The quick brown fox";
$div.html(html);
// Select at the text "quick":
$div.setContentEditableSelection(4, 5);
// Select at the beginning of the contenteditable div:
$div.setContentEditableSelection(0);
// Select at the end of the contenteditable div:
$div.setContentEditableSelection(html.length);
Excuse the long code post, but it may help someone:
$.fn.setContentEditableSelection = function(position, length) {
if (typeof(length) == "undefined") {
length = 0;
}
return this.each(function() {
var $this = $(this);
var editable = this;
var selection;
var range;
var html = $this.html();
html = html.substring(0, position) +
'<a id="cursorStart"></a>' +
html.substring(position, position + length) +
'<a id="cursorEnd"></a>' +
html.substring(position + length, html.length);
console.log(html);
$this.html(html);
// Populates selection and range variables
var captureSelection = function(e) {
// Don't capture selection outside editable region
var isOrContainsAnchor = false,
isOrContainsFocus = false,
sel = window.getSelection(),
parentAnchor = sel.anchorNode,
parentFocus = sel.focusNode;
while (parentAnchor && parentAnchor != document.documentElement) {
if (parentAnchor == editable) {
isOrContainsAnchor = true;
}
parentAnchor = parentAnchor.parentNode;
}
while (parentFocus && parentFocus != document.documentElement) {
if (parentFocus == editable) {
isOrContainsFocus = true;
}
parentFocus = parentFocus.parentNode;
}
if (!isOrContainsAnchor || !isOrContainsFocus) {
return;
}
selection = window.getSelection();
// Get range (standards)
if (selection.getRangeAt !== undefined) {
range = selection.getRangeAt(0);
// Get range (Safari 2)
} else if (
document.createRange &&
selection.anchorNode &&
selection.anchorOffset &&
selection.focusNode &&
selection.focusOffset
) {
range = document.createRange();
range.setStart(selection.anchorNode, selection.anchorOffset);
range.setEnd(selection.focusNode, selection.focusOffset);
} else {
// Failure here, not handled by the rest of the script.
// Probably IE or some older browser
}
};
// Slight delay will avoid the initial selection
// (at start or of contents depending on browser) being mistaken
setTimeout(function() {
var cursorStart = document.getElementById('cursorStart');
var cursorEnd = document.getElementById('cursorEnd');
// Don't do anything if user is creating a new selection
if (editable.className.match(/\sselecting(\s|$)/)) {
if (cursorStart) {
cursorStart.parentNode.removeChild(cursorStart);
}
if (cursorEnd) {
cursorEnd.parentNode.removeChild(cursorEnd);
}
} else if (cursorStart) {
captureSelection();
range = document.createRange();
if (cursorEnd) {
range.setStartAfter(cursorStart);
range.setEndBefore(cursorEnd);
// Delete cursor markers
cursorStart.parentNode.removeChild(cursorStart);
cursorEnd.parentNode.removeChild(cursorEnd);
// Select range
selection.removeAllRanges();
selection.addRange(range);
} else {
range.selectNode(cursorStart);
// Select range
selection.removeAllRanges();
selection.addRange(range);
// Delete cursor marker
document.execCommand('delete', false, null);
}
}
// Register selection again
captureSelection();
}, 10);
});
};
You can leverage selectNodeContents which is supported by modern browsers.
var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();
In Firefox you might have the text of the div in a child node (o_div.childNodes[0])
var range = document.createRange();
range.setStart(o_div.childNodes[0],last_caret_pos);
range.setEnd(o_div.childNodes[0],last_caret_pos);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
I may be late to the party with this one, but maybe instead of just manipulating the dom on the frontend you could store whatever the current value of the tag you are edititing in a variable that is not the value that is being rendered to the dom. Then you can detect a page refresh and change the value of the innerHTML of the tag then, or in my case you just need to keep track of the changes and send this to a back end. Perhaps my words won't do any justice so I will write a code example that has worked for my use case.
import React, { ChangeEvent, useEffect, useState } from "react";
interface IParentProps {}
const ParentComp: React.FC<IParentProps> = (props) => {
const [innerValue, setInnerValue] = useState<string>();
const [ghostValue, setGhostValue] = useState<string>();
// create some boolean to detect when the enter key was pressed in the input field so that you
//can remove the input field and add the child component
const handleChange = (event: ChangeEvent<HTMLDivElement>) => {
setInnerValue(event.currentTarget.innerHTML);
setGhostValue(event.currentTarget.innerHTML);
};
const handleGhostChange = (event: ChangeEvent<HTMLDivElement>) => {
setGhostValue(event.currentTarget.innerHTML);
};
//handle screen refresh, or send the ghost value to the backend
useEffect(() => {}, []);
return (
<div>
<input type="text" onChange={handleChange} />
<ChildComponent handleChange={handleGhostChange}>
{innerValue}
</ChildComponent>
</div>
);
};
interface IChildProps {
handleChange: (e: ChangeEvent<HTMLDivElement>) => void;
children: React.ReactNode;
}
const ChildComponent: React.FC<IChildProps> = (props) => {
return (
<p
contentEditable="true"
suppressContentEditableWarning={true}
onInput={props.handleChange}
>
{props.children}
</p>
);
};
I hope this makes sense if you would like me to revise the answer without the typescript bloat I am willing and able. If this works for you guys please let me know I think this is a much simplier solution then trying to reconfigure the cursor how you want it personally.

Categories

Resources