How to implement break lines and paragraphs on contenteditable? - javascript

I’m building a simple text editor for Safari only. I need to implement a very specific behavior:
First enter - Creates <br> tag
Second enter (after <br>) - Create new paragraph
I’m already listening for enter on keypress event and using formatBlock to format paragraphs. How can I check if element before caret is a <br> element, so I can use formatBlock?
By default, Safari adds <div><br></div> on enter keypress, so I need to use preventDefault for first enter too. (code above)
I create new paragraphs using:
$("#content").live("keypress", function(e){
if (e.which == 13) {
document.execCommand("formatBlock", false, "p");
}
});
I can add br's using: ( Make a <br> instead of <div></div> by pressing Enter on a contenteditable )
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
range.setStartAfter(br);
range.setEndAfter(br);
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
return false;
}
UPDATE: User is typing a paragraph like this: <p>This is my paragraph</p>. At enter keypress, code should be <p>This is my paragraph<br></p> (cursor after br). Pressing enter for second time should result on <p>This is my paragraph</p><p></p> (cursor on second paragraph)

You could use keydown, for example:
<div id="textarea"></div>
Then in your script file:
document.getElementById("textarea").addEventListener("keydown",function(e){if(e.keyCode == 32) {ocument.getElementById("textarea").innerHTML+="<br />"} })
And your other stuff

DISCLAIMER: This is tested only on Chromium.
var sel = window.getSelection();
var range = sel.getRangeAt(0);
if ((sel.extentNode.previousElementSibling instanceof HTMLBRElement)
&& range.startOffset == 0)
{
// Do your magic to start a paragraph.
} else {
// Your existing code to add a <br> element since there is no <br> before it.
}

Related

How to place cursor at end of text in text input element in IE [duplicate]

I need to move caret to end of contenteditable node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable elements.
Geowa4's solution will work for a textarea, but not for a contenteditable element.
This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable.
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
It can be used by code similar to:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
If you don't care about older browsers, this one did the trick for me.
// [optional] make sure focus is on the element
yourContentEditableElement.focus();
// select all the content in the element
document.execCommand('selectAll', false, null);
// collapse selection to the end
document.getSelection().collapseToEnd();
There is also another problem.
The Nico Burns's solution works if the contenteditable div doesn't contain other multilined elements.
For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems.
In order to solve them, I've arranged the following solution, that is an improvement of the Nico's one:
//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Usage:
var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
In this way, the cursor is surely positioned at the end of the last element, eventually nested.
EDIT #1: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named void elements, and in this question there are some methods on how to test if an element is void. So, assuming that exists a function called canContainText that returns true if the argument is not a void element, the following line of code:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
should be replaced with:
canContainText(getLastChildElement(contentEditableElement))
EDIT #2: The above code is fully updated, with every changes described and discussed
It's possible to do set cursor to the end through the range:
setCaretToEnd(target/*: HTMLDivElement*/) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(target);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
target.focus();
range.detach(); // optimization
// set scroll to the end if multiline
target.scrollTop = target.scrollHeight;
}
A shorter and readable version using only selection (without range):
function setEndOfContenteditable(elem) {
let sel = window.getSelection();
sel.selectAllChildren(elem);
sel.collapseToEnd();
}
<p id="pdemo" contenteditable>
A paragraph <span id="txt1" style="background-color: #0903">span text node <i>span italic</i></span> a paragraph.
<p>
<button onclick="pdemo.focus(); setEndOfContenteditable(txt1)">set caret</button>
Quite useful: https://javascript.info/selection-range
Moving cursor to the end of editable span in response to focus event:
moveCursorToEnd(el){
if(el.innerText && document.createRange)
{
window.setTimeout(() =>
{
let selection = document.getSelection();
let range = document.createRange();
range.setStart(el.childNodes[0],el.innerText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
,1);
}
}
And calling it in event handler (React here):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
I had a similar problem trying to make a element editable. It was possible in Chrome and FireFox but in FireFox the caret either went to the beginning of the input or it went one space after the end of the input. Very confusing to the end-user I think, trying to edit the content.
I found no solution trying several things. Only thing that worked for me was to "go around the problem" by putting a plain old text-input INSIDE my . Now it works. Seems like "content-editable" is still bleeding edge tech, which may or may not work as you would like it to work, depending on the context.
The problem with contenteditable <div> and <span> is resolved when you start typing in it initially. One workaround for this could be triggering a focus event on your div element and on that function, clear, and refill what was already in the div element. This way the problem is resolved and finally you can place the cursor at the end using range and selection. Worked for me.
moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;
if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}
In HTML code:
<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>

Wrap an html tag after clicking a toolbar button using js or jquery

I want to do something similar to what this website and wordpress does. When a user highlights text on the screen, then clicks a button on the toolbar it will wrap an html tag around the text. In jquery I would probably use the .wrap class but how would I detect if the user highlighted something.
For example, when the user writes Hello World then clicks on the bold button it will say <b>Hello World</b>
This mainly requires (1) accessing the selectionStart and selectionEnd properties of the input/textarea element and (2) replacing the substring of the value property across that range with the same text, but wrapped in the desired start and end tags. Also, I think it makes sense to reselect the replaced text, which requires a couple of calls to select() and setSelectionRange(). Also, if there's no selection (meaning start equals end) it's probably a good idea to do nothing at all.
window.selWrapBold = function(id) { selWrap(id,'<b>','</b>'); };
window.selWrapItalic = function(id) { selWrap(id,'<i>','</i>'); };
window.selWrap = function(id,startTag,endTag) {
let elem = document.getElementById(id);
let start = elem.selectionStart;
let end = elem.selectionEnd;
let sel = elem.value.substring(start,end);
if (sel==='') return;
let replace = startTag+sel+endTag;
elem.value = elem.value.substring(0,start)+replace+elem.value.substring(end);
elem.select();
elem.setSelectionRange(start,start+replace.length);
} // end selWrap()
<input type="button" value="bold" onclick="selWrapBold('ta1');"/>
<input type="button" value="italic" onclick="selWrapItalic('ta1');"/>
<br/>
<textarea id="ta1"></textarea>
Get the text of the html element which is wrapping the text, then add as html the text embedded in the <b> tag.
See jQuery DOM Manipulation for tutorials.
I used this question to get the selected text. And this question to
get the element with selected text in it. I combined them in a single function.
function updateHighlightedText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
var node = $(window.getSelection().anchorNode.parentNode); //Get the selected node
node.html(node.text().replace(text, "<b>"+text+"</b>")); //Update the node
}

Placing focus on selected text in div FF

I want to automatically select a piece of text so that the user can use ctrl + c to copy it to its clipboard.
In order to do this, I've attached some event handlers to a couple of inputs and a couple of divs (with tabindex="0").
However, if I select a piece of text with javascript, the browser indicates a selection but keeps the focus on the input.
If I try to achieve the same thing but with the div being the trigger, It works.
This behavior is only in FireFox.
In my jsfiddle (or in the snippet below) put the focus on the first input, press a random key (which selects the text), and try to copy paste it in the lower input.
Then try to do the same but with clicking the div. (clicking the div will also select the text).
var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
selectText(document.getElementById("selectme"));
});
var div = document.getElementById("clickme");
div.addEventListener("click", function(evt){
selectText(document.getElementById("selectme"));
});
var selectText = function(element){
var range, selection;
if(document.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if(window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
element.focus();
}
<input id="my-input"/>
<div id="selectme">Texttexttexttext</div>
<div tabindex="0" id="clickme">CLICK ME</div>
<input />
If you call evt.target.blur(); first, the input will lose its focus before focussing the div.
Your function will look like:
var input = document.getElementById("my-input");
input.addEventListener("keydown", function(evt){
evt.target.blur();
selectText(document.getElementById("selectme"));
});

How to move cursor to end of contenteditable entity

I need to move caret to end of contenteditable node like on Gmail notes widget.
I read threads on StackOverflow, but those solutions are based on using inputs and they doesn't work with contenteditable elements.
Geowa4's solution will work for a textarea, but not for a contenteditable element.
This solution is for moving the caret to the end of a contenteditable element. It should work in all browsers which support contenteditable.
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
It can be used by code similar to:
elem = document.getElementById('txt1');//This is the element that you want to move the caret to the end of
setEndOfContenteditable(elem);
If you don't care about older browsers, this one did the trick for me.
// [optional] make sure focus is on the element
yourContentEditableElement.focus();
// select all the content in the element
document.execCommand('selectAll', false, null);
// collapse selection to the end
document.getSelection().collapseToEnd();
There is also another problem.
The Nico Burns's solution works if the contenteditable div doesn't contain other multilined elements.
For instance, if a div contains other divs, and these other divs contain other stuff inside, could occur some problems.
In order to solve them, I've arranged the following solution, that is an improvement of the Nico's one:
//Namespace management idea from http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-1/
(function( cursorManager ) {
//From: http://www.w3.org/TR/html-markup/syntax.html#syntax-elements
var voidNodeTags = ['AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'KEYGEN', 'LINK', 'MENUITEM', 'META', 'PARAM', 'SOURCE', 'TRACK', 'WBR', 'BASEFONT', 'BGSOUND', 'FRAME', 'ISINDEX'];
//From: https://stackoverflow.com/questions/237104/array-containsobj-in-javascript
Array.prototype.contains = function(obj) {
var i = this.length;
while (i--) {
if (this[i] === obj) {
return true;
}
}
return false;
}
//Basic idea from: https://stackoverflow.com/questions/19790442/test-if-an-element-can-contain-text
function canContainText(node) {
if(node.nodeType == 1) { //is an element node
return !voidNodeTags.contains(node.nodeName);
} else { //is not an element node
return false;
}
};
function getLastChildElement(el){
var lc = el.lastChild;
while(lc && lc.nodeType != 1) {
if(lc.previousSibling)
lc = lc.previousSibling;
else
break;
}
return lc;
}
//Based on Nico Burns's answer
cursorManager.setEndOfContenteditable = function(contentEditableElement)
{
while(getLastChildElement(contentEditableElement) &&
canContainText(getLastChildElement(contentEditableElement))) {
contentEditableElement = getLastChildElement(contentEditableElement);
}
var range,selection;
if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
{
range = document.createRange();//Create a range (a range is a like the selection but invisible)
range.selectNodeContents(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
selection = window.getSelection();//get the selection object (allows you to change selection)
selection.removeAllRanges();//remove any selections already made
selection.addRange(range);//make the range you have just created the visible selection
}
else if(document.selection)//IE 8 and lower
{
range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
range.select();//Select the range (make it the visible selection
}
}
}( window.cursorManager = window.cursorManager || {}));
Usage:
var editableDiv = document.getElementById("my_contentEditableDiv");
cursorManager.setEndOfContenteditable(editableDiv);
In this way, the cursor is surely positioned at the end of the last element, eventually nested.
EDIT #1: In order to be more generic, the while statement should consider also all the other tags which cannot contain text. These elements are named void elements, and in this question there are some methods on how to test if an element is void. So, assuming that exists a function called canContainText that returns true if the argument is not a void element, the following line of code:
contentEditableElement.lastChild.tagName.toLowerCase() != 'br'
should be replaced with:
canContainText(getLastChildElement(contentEditableElement))
EDIT #2: The above code is fully updated, with every changes described and discussed
It's possible to do set cursor to the end through the range:
setCaretToEnd(target/*: HTMLDivElement*/) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNodeContents(target);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
target.focus();
range.detach(); // optimization
// set scroll to the end if multiline
target.scrollTop = target.scrollHeight;
}
A shorter and readable version using only selection (without range):
function setEndOfContenteditable(elem) {
let sel = window.getSelection();
sel.selectAllChildren(elem);
sel.collapseToEnd();
}
<p id="pdemo" contenteditable>
A paragraph <span id="txt1" style="background-color: #0903">span text node <i>span italic</i></span> a paragraph.
<p>
<button onclick="pdemo.focus(); setEndOfContenteditable(txt1)">set caret</button>
Quite useful: https://javascript.info/selection-range
Moving cursor to the end of editable span in response to focus event:
moveCursorToEnd(el){
if(el.innerText && document.createRange)
{
window.setTimeout(() =>
{
let selection = document.getSelection();
let range = document.createRange();
range.setStart(el.childNodes[0],el.innerText.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
,1);
}
}
And calling it in event handler (React here):
onFocus={(e) => this.moveCursorToEnd(e.target)}}
I had a similar problem trying to make a element editable. It was possible in Chrome and FireFox but in FireFox the caret either went to the beginning of the input or it went one space after the end of the input. Very confusing to the end-user I think, trying to edit the content.
I found no solution trying several things. Only thing that worked for me was to "go around the problem" by putting a plain old text-input INSIDE my . Now it works. Seems like "content-editable" is still bleeding edge tech, which may or may not work as you would like it to work, depending on the context.
The problem with contenteditable <div> and <span> is resolved when you start typing in it initially. One workaround for this could be triggering a focus event on your div element and on that function, clear, and refill what was already in the div element. This way the problem is resolved and finally you can place the cursor at the end using range and selection. Worked for me.
moveCursorToEnd(e : any) {
let placeholderText = e.target.innerText;
e.target.innerText = '';
e.target.innerText = placeholderText;
if(e.target.innerText && document.createRange)
{
let range = document.createRange();
let selection = window.getSelection();
range.selectNodeContents(e.target);
range.setStart(e.target.firstChild,e.target.innerText.length);
range.setEnd(e.target.firstChild,e.target.innerText.length);
selection.removeAllRanges();
selection.addRange(range);
}
}
In HTML code:
<div contentEditable="true" (focus)="moveCursorToEnd($event)"></div>

How to get selected text from a textbox control with JavaScript

I have a textbox and a link button.
When I write some text, select some of it and then click the link button, the selected text from textbox must be show with a message box.
How can I do it?
When I click the submit button for the textbox below, the message box must show Lorem ipsum. Because "Lorem ipsum" is selected in the area.
If I select any text from the page and click the submit button it is working, but if I write a text to textbox and make it, it's not. Because when I click to another space, the selection of textbox is canceled.
Now problem is that, when I select text from textbox and click any other control or space, the text, which is selected, must still be selected.
How is it to be done?
OK, here is the code I have:
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{ // Standards-compliant version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{ // Internet Explorer version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
The problem is, although the code I give for Internet Explorer is given on a lot of sites, I cannot make it work on my copy of Internet Explorer 6 on my current system. Perhaps it will work for you, and that's why I give it.
The trick you look for is probably the .focus() call to give the focus back to the textarea, so the selection is reactivated.
I got the right result (the selection content) with the onKeyDown event:
document.onkeydown = function (e) { ShowSelection(); }
So the code is correct. Again, the issue is to get the selection on click on a button... I continue to search.
I didn't have any success with a button drawn with a li tag, because when we click on it, Internet Explorer deselects the previous selection. The above code works with a simple input button, though...
Here's a much simpler solution, based on the fact that text selection occurs on mouseup, so we add an event listener for that:
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection().toString();
});
<textarea>
Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>
This works in all browsers.
If you also want to handle selection via the keyboard, add another event listener for keyup, with the same code.
If it weren't for this Firefox bug filed back in 2001 (yes, 14 years ago), we could replace the value assigned to window.mySelection with window.getSelection().toString(), which works in IE9+ and all modern browsers, and also gets the selection made in non-textarea parts of the DOM.
function disp() {
var text = document.getElementById("text");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />
For Opera, Firefox and Safari, you can use the following function:
function getTextFieldSelection(textField) {
return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}
Then, you just pass a reference to a text field element (like a textarea or input element) to the function:
alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));
Or, if you want <textarea> and <input> to have a getSelection() function of their own:
HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
var ss = this.selectionStart;
var se = this.selectionEnd;
if (typeof ss === "number" && typeof se === "number") {
return this.value.substring(this.selectionStart, this.selectionEnd);
}
return "";
};
Then, you'd just do:
alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());
for example.
I am a big fan of jQuery-textrange.
Below is a very small, self-contained, example. Download jquery-textrange.js and copy it to the same folder.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>jquery-textrange</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="jquery-textrange.js"></script>
<script>
/* Run on document load */
$(document).ready(function() {
/* Run on any change of 'textarea' **/
$('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
/* The magic is on this line **/
var range = $(this).textrange();
/* Stuff into selectedId. I wanted to
store this is a input field so it
can be submitted in a form. */
$('#selectedId').val(range.text);
});
});
</script>
</head>
<body>
The smallest example possible using
<a href="https://github.com/dwieeb/jquery-textrange">
jquery-textrange
</a><br/>
<textarea id="textareaId">Some random content.</textarea><br/>
<input type="text" id="selectedId"></input>
</body>
</html>
// jQuery
var textarea = $('#post-content');
var selectionStart = textarea.prop('selectionStart');
var selectionEnd = textarea.prop('selectionEnd');
var selection = (textarea.val()).substring(selectionStart, selectionEnd);
// JavaScript
var textarea = document.getElementById("post-content");
var selection = (textarea.value).substring(textarea.selectionStart, textarea.selectionEnd);

Categories