Text selection in div(contenteditable) when double click - javascript

I have div with some text and contenteditable="true". When I single click on this div - works some my scripts, it is not very important. And when I double click on this div - need to edit text in div. Edit text need to be only after double click, not after single. And very imortant, when I double click on div - caret need stay under mouse cursor. No need selection text. I found some script for single/double. But have problem. When I double click on div - text are selection. Selection no need. Need editor caret where I clicked. I do not understand how.
http://jsfiddle.net/X6auM/

Every current major browser provides an API to create a range from a mouse event, although there are four different code branches needed.
Here is some background:
https://stackoverflow.com/a/10659990/96100
https://stackoverflow.com/a/12705894/96100
Creating a collapsed range from a pixel position in FF/Webkit
Here's a demo: http://jsfiddle.net/timdown/krtTD/10/
And here's some code:
function getMouseEventCaretRange(evt) {
var range, x = evt.clientX, y = evt.clientY;
// Try the simple IE way first
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToPoint(x, y);
}
else if (typeof document.createRange != "undefined") {
// Try Mozilla's rangeOffset and rangeParent properties,
// which are exactly what we want
if (typeof evt.rangeParent != "undefined") {
range = document.createRange();
range.setStart(evt.rangeParent, evt.rangeOffset);
range.collapse(true);
}
// Try the standards-based way next
else if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse(true);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
}
return range;
}
function selectRange(range) {
if (range) {
if (typeof range.select != "undefined") {
range.select();
} else if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
document.getElementById("editor").ondblclick = function(evt) {
evt = evt || window.event;
this.contentEditable = true;
this.focus();
var caretRange = getMouseEventCaretRange(evt);
// Set a timer to allow the selection to happen and the dust settle first
window.setTimeout(function() {
selectRange(caretRange);
}, 10);
return false;
};

$('p').dblclick(function(event) {
$this = $(this);
$this.attr('contenteditable', "true");
$this.blur();
$this.focus();
});
http://jsfiddle.net/krtTD/90/

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<!-- <link rel="stylesheet" href="../tailwind.css" /> -->
</head>
<body>
<div id="editor" style="user-select:none;" contenteditable="false">Some editableasa text. Double click to eadsit</div>
<script>
function getMouseEventCaretRange(evt) {
var range, x = evt.clientX, y = evt.clientY;
// Try the simple IE way first
if (document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToPoint(x, y);
}
else if (typeof document.createRange != "undefined") {
// Try Mozilla's rangeOffset and rangeParent properties, which are exactly what we want
if (typeof evt.rangeParent != "undefined") {
range = document.createRange();
range.setStart(evt.rangeParent, evt.rangeOffset);
range.collapse(true);
}
// Try the standards-based way next
else if (document.caretPositionFromPoint) {
var pos = document.caretPositionFromPoint(x, y);
range = document.createRange();
range.setStart(pos.offsetNode, pos.offset);
range.collapse(true);
}
// Next, the WebKit way
else if (document.caretRangeFromPoint) {
range = document.caretRangeFromPoint(x, y);
}
}
return range;
}
function selectRange(range) {
if (range) {
if (typeof range.select != "undefined") {
range.select();
} else if (typeof window.getSelection != "undefined") {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}
document.getElementById("editor").ondblclick = function (evt) {
evt = evt || window.event;
this.contentEditable = true;
this.focus();
var caretRange = getMouseEventCaretRange(evt);
selectRange(caretRange);
this.style = ""
};
</script>
</body>
</html>
An improvement of accepted answer that does not create the temp flash it uses css user-select property to it's advantage

Related

How to shift cursor position in a text using javascript [duplicate]

Does anybody know how to move the keyboard caret in a textbox to a particular position?
For example, if a text-box (e.g. input element, not text-area) has 50 characters in it and I want to position the caret before character 20, how would I go about it?
This is in differentiation from this question: jQuery Set Cursor Position in Text Area , which requires jQuery.
Excerpted from Josh Stodola's Setting keyboard caret Position in a Textbox or TextArea with Javascript
A generic function that will allow you to insert the caret at any position of a textbox or textarea that you wish:
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
The first expected parameter is the ID of the element you wish to insert the keyboard caret on. If the element is unable to be found, nothing will happen (obviously). The second parameter is the caret positon index. Zero will put the keyboard caret at the beginning. If you pass a number larger than the number of characters in the elements value, it will put the keyboard caret at the end.
Tested on IE6 and up, Firefox 2, Opera 8, Netscape 9, SeaMonkey, and Safari. Unfortunately on Safari it does not work in combination with the onfocus event).
An example of using the above function to force the keyboard caret to jump to the end of all textareas on the page when they receive focus:
function addLoadEvent(func) {
if(typeof window.onload != 'function') {
window.onload = func;
}
else {
if(func) {
var oldLoad = window.onload;
window.onload = function() {
if(oldLoad)
oldLoad();
func();
}
}
}
}
// The setCaretPosition function belongs right here!
function setTextAreasOnFocus() {
/***
* This function will force the keyboard caret to be positioned
* at the end of all textareas when they receive focus.
*/
var textAreas = document.getElementsByTagName('textarea');
for(var i = 0; i < textAreas.length; i++) {
textAreas[i].onfocus = function() {
setCaretPosition(this.id, this.value.length);
}
}
textAreas = null;
}
addLoadEvent(setTextAreasOnFocus);
The link in the answer is broken, this one should work (all credits go to blog.vishalon.net):
http://snipplr.com/view/5144/getset-cursor-in-html-textarea/
In case the code gets lost again, here are the two main functions:
function doGetCaretPosition(ctrl)
{
var CaretPos = 0;
if (ctrl.selectionStart || ctrl.selectionStart == 0)
{// Standard.
CaretPos = ctrl.selectionStart;
}
else if (document.selection)
{// Legacy IE
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
return (CaretPos);
}
function setCaretPosition(ctrl,pos)
{
if (ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange)
{
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon #kd7's code here's what I've come up with.
Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera
Cross-browser caret positioning technique (example: moving the cursor to the END)
// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)
setCaretPosition('IDHERE', 10); // example
The meat and potatoes is basically #kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.
In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.
function setCaretPosition(elemId, caretPos) {
var el = document.getElementById(elemId);
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;
}
}
}
}
I found an easy way to fix this issue, tested in IE and Chrome:
function setCaret(elemId, caret)
{
var elem = document.getElementById(elemId);
elem.setSelectionRange(caret, caret);
}
Pass text box id and caret position to this function.
I've adjusted the answer of kd7 a little bit because elem.selectionStart will evaluate to false when the selectionStart is incidentally 0.
function setCaretPosition(elem, caretPos) {
var range;
if (elem.createTextRange) {
range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
elem.focus();
if (elem.selectionStart !== undefined) {
elem.setSelectionRange(caretPos, caretPos);
}
}
}
If you need to focus some textbox and your only problem is that the entire text gets highlighted whereas you want the caret to be at the end, then in that specific case, you can use this trick of setting the textbox value to itself after focus:
$("#myinputfield").focus().val($("#myinputfield").val());
function SetCaretEnd(tID) {
tID += "";
if (!tID.startsWith("#")) { tID = "#" + tID; }
$(tID).focus();
var t = $(tID).val();
if (t.length == 0) { return; }
$(tID).val("");
$(tID).val(t);
$(tID).scrollTop($(tID)[0].scrollHeight); }
I would fix the conditions like below:
function setCaretPosition(elemId, caretPos)
{
var elem = document.getElementById(elemId);
if (elem)
{
if (typeof elem.createTextRange != 'undefined')
{
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else
{
if (typeof elem.selectionStart != 'undefined')
elem.selectionStart = caretPos;
elem.focus();
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>set caret position</title>
<script type="application/javascript">
//<![CDATA[
window.onload = function ()
{
setCaret(document.getElementById('input1'), 13, 13)
}
function setCaret(el, st, end)
{
if (el.setSelectionRange)
{
el.focus();
el.setSelectionRange(st, end);
}
else
{
if (el.createTextRange)
{
range = el.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', st);
range.select();
}
}
}
//]]>
</script>
</head>
<body>
<textarea id="input1" name="input1" rows="10" cols="30">Happy kittens dancing</textarea>
<p> </p>
</body>
</html>
HTMLInputElement.setSelectionRange( selectionStart, selectionEnd );
// References
var e = document.getElementById( "helloworldinput" );
// Move caret to beginning on focus
e.addEventListener( "focus", function( event )
{
// References
var e = event.target;
// Action
e.setSelectionRange( 0, 0 ); // Doesn’t work for focus event
window.setTimeout( function()
{
e.setSelectionRange( 0, 0 ); // Works
//e.setSelectionRange( 1, 1 ); // Move caret to second position
//e.setSelectionRange( 1, 2 ); // Select second character
}, 0 );
}, false );
Browser compatibility (only for types: text, search, url, tel and password):
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange#Specifications

Move caret right after input in contenteditable when caret is inside the input at the end of it

I am having this problem. I am inserting input elements in a contenteditable div. The caret is in the input at the last position. I would like some help how to move the cursor right after that input by executing some function. You will see in my code that I have to click (justInserted.click()) to make some resizing happen. If I remove the justInserted.focus() then the caret is always at the start of the contenteditable. I would like to have a function that finds that the caret is in a specific input in the contenteditable and when I call it, it will put the caret right after that specific input. Any help is appreciated :)
My insert at caret looks like this:
this.insertNodeAtCursor = function(node) {
var sel, range, html;
function containerIsEditable(selection) {
return $(selection.anchorNode).parent().hasClass("editable");
}
if (window.getSelection) {
sel = window.getSelection();
// only if it is a caret otherwise it inserts
// anywhere!
if (containerIsEditable(sel) && sel.getRangeAt
&& sel.rangeCount) {
var previousPosition = sel.getRangeAt(0).startOffset;
sel.getRangeAt(0).insertNode(node);
}
}
else if (document.selection
&& document.selection.createRange) {
range = document.selection.createRange();
html = (node.nodeType == 3) ? node.data
: node.outerHTML;
range.pasteHTML(html);
}
};
and the function that adds the input is this:
this.addInput = function(suggestEntry, query) {
var id = suggestEntry.id;
var nodeClass = suggestEntry.nodeClass;
var uuid = suggestEntry.uuid;
var clause = null;
if (nodeClass === "Entity"){
clause = new Entity();
clause.uuid = uuid;
clause.id = id;
clause.text = suggestEntry.text;
}
var input = clause.toEditorElementHtml();
this.insertNodeAtCursor(input);
var rand = Math.floor((Math.random() * 1000000) + 1);
input.setAttribute('id', "rand-" + rand);
$rootScope.$broadcast("remove:query",query);
var autoSizingInputs = $('input[autosize="autosize"]');
var justInserted = $('#rand-' + rand);
$compile(autoSizingInputs)($scope);
justInserted.focus();
justInserted.click(); // a bit hacky :/
$(justInserted).val($(justInserted).val() + "");
};
Here's a snippet with a function that moves the caret right after the focused input. I've tested it in Chrome Version 47.0.2526.111 m, Firefox 43.0.4 and IE 11.
function setCaretAfterFocusedInput(container) {
var input = container.querySelector('input:focus');
if (input) {
container.focus(); // required for firefox
setCaretAfter(input);
}
}
function setCaretAfter(element) {
if (window.getSelection) {
var range = document.createRange();
range.setStartAfter(element);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
}
// for demonstration purposes
document.addEventListener('keyup', function(e) {
if (e.which === 16) { // on SHIFT
var container = document.querySelector('div[contenteditable]');
setCaretAfterFocusedInput(container);
}
});
<p>When an input is focused, press shift to move the caret right after the input.</p>
<div contenteditable>
<input type="text" value="input1"><input type="text" value="no whitespace before this">
<br><br>some text<input type="text" value="input3">more text
<br><br>
<input type="text"><p>text in a paragraph, no whitespace before this</p>
<input type="text">
<p>text in a paragraph</p>
</div>

How to prevent the caret jumping to the end of the whole text in contenteditable div after pasting the HTML words in the middle of the original text?

Summary/Background
I'm trying to make a contenteditable div and when it was pasted by the HTML words, I hope that it could be transferred into plain text and the caret could jump to the end of the pasted HTML words automatically.
My try
I have tried to make it, and below is my code I have typed.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function stripHTML(input){
var output = '';
if(typeof(input) == "string"){
output = input.replace(/(<([^>]+)>)/ig, "");
}
return output;
}
$(function(){
$("#text").focus(function(event){
setItv = setInterval('clearHTML()', 1);
});
$("#text").blur(function(event){
clearInterval(setItv);
});
});
function clearHTML(){
var patt = /(<([^>]+)>)/ig;
var input = $("#text").html();
if(input.search(patt) >= 0){
var output = '';
if(typeof(input) == "string"){
output = stripHTML(input);
}
$("#text").html(output);
}
}
</script>
<div contenteditable="true" style="border: 1px #000 solid; width: 300px;
height: 100px;" id="text">Hello, world!</div>
</body>
</html>
Issue
The biggest issue is the cursor placement. After pasting the HTML in the middle of the original text (e.g., paste between “Hello” and “world”), the caret would jump to the end of the whole text not the end of the pasted HTML. Normally, when we paste a snippet of words in the middle of the original text, the caret would jump to the end of the pasted words, not the end of the whole text. But in this case I don't know why it jumps to the end of the whole text automatically.
And the secondary issue is that the setInterval function. Maybe it doesn't cause any problem, but the way of scripting is extremely unprofessional and it may impact the efficiency of the program.
Question
How to prevent the caret from jumping to the end of the whole text in contenteditable div after pasting the HTML words in the middle of the original text?
How to optimize the scripting without using the setInterval function?
As a starting point, I would suggest the following improvements:
Check directly for the presence of elements in your editable content rather than using a regular expression on the innerHTML property. This will improve performance because innerHTML is slow. You could do this using the standard DOM method getElementsByTagName(). If you prefer to use jQuery, which will be slightly less efficient, you could use $("#text").find("*"). Even simpler and faster would be to check that your editable element has a single child which is a text node.
Strip the HTML by replacing the element's content with a text node containing the element's textContent property. This will more reliable than replacing HTML tags with a regular expression.
Store the selection as character offsets before stripping HTML tags and restore it afterwards. I have previously posted code on Stack Overflow to do this.
Do the HTML stripping when relevant events fire (I suggest keypress, keyup, input and paste for starters). I'd keep the setInterval() with a less frequent interval to deal with other cases not covered by those events
The following snippet contains all these improvements:
var saveSelection, restoreSelection;
if (window.getSelection && document.createRange) {
saveSelection = function(containerEl) {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;
return {
start: start,
end: start + range.toString().length
};
};
restoreSelection = function(containerEl, savedSel) {
var charIndex = 0, range = document.createRange();
range.setStart(containerEl, 0);
range.collapse(true);
var nodeStack = [containerEl], node, foundStart = false, stop = false;
while (!stop && (node = nodeStack.pop())) {
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);
stop = true;
}
charIndex = nextCharIndex;
} else {
var i = node.childNodes.length;
while (i--) {
nodeStack.push(node.childNodes[i]);
}
}
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
} else if (document.selection) {
saveSelection = function(containerEl) {
var selectedTextRange = document.selection.createRange();
var preSelectionTextRange = document.body.createTextRange();
preSelectionTextRange.moveToElementText(containerEl);
preSelectionTextRange.setEndPoint("EndToStart", selectedTextRange);
var start = preSelectionTextRange.text.length;
return {
start: start,
end: start + selectedTextRange.text.length
}
};
restoreSelection = function(containerEl, savedSel) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(containerEl);
textRange.collapse(true);
textRange.moveEnd("character", savedSel.end);
textRange.moveStart("character", savedSel.start);
textRange.select();
};
}
$(function(){
var setInv;
var $text = $("#text");
$text.focus(function(event){
setItv = setInterval(clearHTML, 200);
});
$text.blur(function(event){
clearInterval(setItv);
});
$text.on("paste keypress keyup input", function() {
// Allow a short delay so that paste and keypress events have completed their default action bewfore stripping HTML
setTimeout(clearHTML, 1)
});
});
function clearHTML() {
var $el = $("#text");
var el = $el[0];
if (el.childNodes.length != 1 || el.firstChild.nodeType != 3 /* Text node*/) {
var savedSel = saveSelection(el);
$el.text( $el.text() );
restoreSelection(el, savedSel);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div contenteditable="true" style="border: 1px #000 solid; width: 300px;
height: 100px;" id="text">Hello, world!</div>

Bold a specific text inside a contenteditable div

I have this in my contenteditable div. Whenever I type #something, then type space, I would like to bold that word instantly in that div.
E.g.
This is my message. #lol. I would like to bold the hashtag.
Below is the code I have
<div id="message" name="message" contenteditable="true"></div>
$('#message').keyup(function(e){
var len = $(this).val().length;
if ($(this).val().substring(length - 1, 1) == '#') {
}
//detect space
if(e.keyCode == 32){
}
});
I am using jquery. How do i go about doing so?
Using contenteditable = "true" may be tricky, but this is a possible solution:
The text is bold when a word is preceded by #
Example: hello #world, this is a #sample
HTML:
<div id="divEditable" contenteditable="true"></div>
JavaScript: jsbin.com/zisote
We are going to split the code, but actually it is wrapped in an IIFE
/*** Cached private variables ***/
var _break = /<br\s?\/?>$/g,
_rxword = /(#[\w]+)$/gm,
_rxboldDown = /<\/b>$/gm,
_rxboldUp = /<\/b>(?!<br\s?\/?>)([\w]+)(?:<br\s?\/?>)?$/,
_rxline = /(<br\s?\/?>)+(?!<b>)(<\/b>$)+/g;
/*** Handles the event when a key is pressed ***/
$(document).on("keydown.editable", '.divEditable', function (e) {
//fixes firefox NodeContent which ends with <br>
var html = this.innerHTML.replace(_break, ""),
key = (e.which || e.keyCode),
dom = $(this);
//space key was pressed
if (key == 32 || key == 13) {
//finds the # followed by a word
if (_rxword.test(dom.text()))
dom.data("_newText", html.replace(_rxword, "<b>$1</b> "));
//finds the end of bold text
if (_rxboldDown.test(html))
dom.data("_newText", html + " ");
}
//prevents the bold NodeContent to be cached
dom.attr("contenteditable", false).attr("contenteditable", true);
});
/*** Handles the event when the key is released ***/
$(document).on("keyup.editable", '.divEditable', function (e) {
var dom = $(this),
newText = dom.data("_newText"),
innerHtml = this.innerHTML,
html;
//resets the NodeContent
if (!dom.text().length || innerHtml == '<br>') {
dom.empty();
return false;
}
//fixes firefox issue when text must follow with bold
if (!newText && _rxboldUp.test(innerHtml))
newText = innerHtml.replace(_rxboldUp, "$1</b>");
//fixes firefox issue when space key is rendered as <br>
if (!newText && _rxline.test(innerHtml)) html = innerHtml;
else if (newText && _rxline.test(newText)) html = newText;
if (html) newText = html.replace(_rxline, "$2$1");
if (newText && newText.length) {
dom.html(newText).removeData("_newText");
placeCaretAtEnd(this);
}
});
/*** Sets the caret position at end of NodeContent ***/
function placeCaretAtEnd (dom) {
var range, sel;
dom.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
range = document.createRange();
range.selectNodeContents(dom);
range.collapse(false);
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
//this handles the text selection in IE
range = document.body.createTextRange();
range.moveToElementText(dom);
range.collapse(false);
range.select();
}
}
You can play with live code here: jsbin.com/zisote
Here is a sample. An editable div is not a good idea though. Try to change this. A textarea maybe is better...
http://jsfiddle.net/blackjim/h9dck/5/
function makeBold(match, p1, p2, p3, offset, string) {
return p1+'<b>' + p2 + '</b>'+p3;
};
$('#message').keyup(function (e) {
var $this = $(this);
//detect space
if (e.keyCode == 32) {
var innerHtml = $this.html();
innerHtml = innerHtml.replace(/(.*[\s|($nbsp;)])(#\w+)(.*)/g, makeBold);
if(innerHtml !== $this.html()){
$this.html(innerHtml)
.focus();
}
}
});

Inserting HTML at cursors position and moving cursor to end of inserted html with javascript

I am writing a script to insert presaved html content into Gmail's editable iframe in the compose page mentioned below. This script is only to be used in Greasemonkey on Firefox. So I don't need to consider any other browser.
Currently it inserts the text once and then gets bugged. I guess because range.setStart() expects first parameter is a node, which createContextualFragment() does not return.
Is there any other way to add html at current cursor's position and then move cursor to the end of the added html (not to the end of all content)?
https://mail.google.com/mail/?view=cm&fs=1&tf=1&source=mailto&to=example#example.com
function insertTextAtCursor(text) {
var sel, range, html, textNode;
if (window.frames[3].window.frames[0].getSelection()) {
sel = window.frames[3].window.frames[0].getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
textNode = range.createContextualFragment(text);
//textNode = document.createTextNode(text);
range.insertNode( textNode );
range.setStart(textNode, textNode.length);
range.setEnd(textNode, textNode.length);
sel.removeAllRanges();
sel.addRange(range);
window.frames[3].window.frames[0].focus();
}
}
}
Update 1:
If i comment the code to move the cursor after inserting html then its no longer bugged, but the cursor stays in the same place.
//range.setStart(textNode, textNode.length);
//range.setEnd(textNode, textNode.length);
sel.removeAllRanges();
//sel.addRange(range);
got you something.
with the help from this answer, i wrote this:
paste your text/html at the cursor position
move the cursor to the end of the text area
save this as test.html to test it locally
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
})
}
});
var myhtml = '<b> this html will be <i>added</i> to the </b> cursor position (and will move to the end)';
var movetotheendof = '';
$(window).load(function(){
$('#btnpastepre').click(function() {
$('#txtarea').insertAtCaret(myhtml)
movetotheendof = $('#txtarea').val()
$('#txtarea').val("").val(movetotheendof)
})
});
</script>
</head>
<body>
<div id="formcontainer">
<button id="btnpastepre">click to paste</button>
<form id="formulario">
<textarea id="txtarea" cols=60 rows=20></textarea>
</form>
</div>
</body>
</html>
or click here to test it online: http://jsfiddle.net/RASG/Vwwm4/
Now all you have to do is change it according to your needs (gmail or any other site)
EDIT
I forgot that you wanted a GM script :)
Here it is
// ==UserScript==
// #name TESTE 3
// #namespace TESTE 3
// #description TESTE 3
// #require http://code.jquery.com/jquery.min.js
// #include *
// #version 1
// ==/UserScript==
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
}
else {
this.value += myValue;
this.focus();
}
})
}
});
var myhtml = '<b> this html will be <i>added</i> to the </b> cursor position (and will move to the end)';
var movetotheendof = '';
$(window).load(function(){
$('#btnpastepre').click(function() {
$('#txtarea').insertAtCaret(myhtml)
movetotheendof = $('#txtarea').val()
$('#txtarea').val("").val(movetotheendof)
})
})
Just create an html file with this content to test it
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="formcontainer">
<button id="btnpastepre">click to paste</button>
<form id="formulario">
<textarea id="txtarea" cols=60 rows=20></textarea>
</form>
</div>
</body>
</html>

Categories