I'm trying to insert div with text to contenteditable and select the text between the div tags after adding the div:
div.innerHTML +='<div id="id">selecttext</div>'
but this won't select the selecttext
<html>
<head></head>
<body>
<div id="contenteditable" contenteditable></div>
<script>
var contenteditable = document.getElementById("contenteditable");
contenteditable.onkeyup = function (e) {
contenteditable.innerHTML += '<div>Start here</div>';
}
</script>
</body>
</html>
Your question has three parts:
Insert div with text to contenteditable:
contenteditable.innerHTML += '<div id="startHere">Start Here</div>';
Find startHere div:
function findStartHereDiv(contenteditable) {
var childNodes = contenteditable.childNodes;
for(var i = 0; i < childNodes.length; i++) {
if(childNodes[i].id == 'startHere') {
return childNodes[i];
break;
}
}
return null;
}
Select text of startHere div:
function selectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
Is this what you need?
DEMO
Related
I have a text area that users can enter text in. When they select text I'd like to get the row and column of the selected text (or cursor) if they do not select any text.
The example below is using the on focus event. It should use a cursor change or selection change event.
document.getElementById('textarea').onselectionchange = onFocusHandler;
document.getElementById('textarea').onselect = onFocusHandler;
document.getElementById('textarea').onfocus = onFocusHandler;
document.getElementById('textarea').onmouseup = onFocusHandler;
document.getElementById('textarea').onselectionstart = onFocusHandler;
function onFocusHandler(event){
var textarea = document.getElementById('textarea');
var value = textarea.value;
var anchorPosition = 0;
var activePosition = 0;
var userSelection;
var range;
console.log(event.type);
if (window.getSelection) {
//console.log("1");
userSelection = window.getSelection();
//console.log(userSelection);
//range = userSelection.getRangeAt(0);
//console.log(range);
}
else if (document.selection) {
userSelection = document.selection.createRange();
}
console.log("Cursor:" + userSelection.anchorOffset);
return;
if (userSelection.getRangeAt) {
//range = userSelection.getRangeAt(0);
}
else {
range = document.createRange();
range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
//console.log(range);
textarea.focus();
if (textarea.setSelectionRange) {
textarea.setSelectionRange(anchorPosition, activePosition);
}
else {
var range = textarea.createTextRange();
range.collapse(true);
range.moveEnd('character', activePosition);
range.moveStart('character', anchorPosition);
range.select();
}
};
<textarea id="textarea" style="width:100%;height:100px">Hello world.
It's a nice day.
Go outside and get some sun.
</textarea>
<span id="row">Row</span>
I want to know how to select Highlighted text using JQuery selector.
For example, to select elements with a class, you use .class, for IDs, you use #id.
What do I use for highlighted text so that I can (for example) hide them:
$("Highlighted text").hide();
What is the highlighted text selector, and how to hide highlighted text?
This is one your are looking for i believe:
text = window.getSelection().toString();
DEMO
Hide selected/highlighted text javascript
You have to get parent of Element from DOM:
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
NEW DEMO
Update
Fixed demo to hide text we have to find startOffset
function getStartOffset() {
var sel = document.selection, range, rect;
var x = 0, y = 0;
if (sel) {
if (sel.type != "Control") {
range = sel.createRange();
range.collapse(true);
}
} else if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
range = sel.getRangeAt(0).cloneRange();
if (range.getClientRects) {
range.collapse(true);
}
}
}
return range.startOffset;
}
Updated DEMO
if($("idDiv").html().contains('Highlighted text')==true)
{
var a=$("#idDiv").html();
a=a.replace("Highlighted text","<p id='highlightedtext'>Highlighted text</p>");
$("#idDiv").html(a);
$("#highlightedtext").hide();
}
The above code check the highlighted text from the div and if it found it set that text in p tag with id and using that id you can hide it
I have a text field which can be edited using click and i am doing it in jQuery.
Now i was wondering how can i select all the text in box when i click EDIT button
Fiddle Link
Code for edit
$('.edit').click(function () {
$(this).siblings('.edit-section').attr('contenteditable', 'true');
$(this).siblings('.edit-section').attr('style', 'border:2px solid;');
$(this).attr('style', 'display:none;');
$(this).siblings('.done').attr('style', 'display:li;');
});
I cannot add separate click function for .edit-section
Try,
$('.edit,.done').click(function () {
var section = $(this).siblings('.edit-section');
var isEdit = $(this).is('.edit');
section.prop('contenteditable',isEdit).css('border',isEdit?"2px solid":"none");
$('.edit').toggle(!isEdit);
$('.done').toggle(isEdit);
if(isEdit){section.focus(); document.execCommand('selectAll',false,null); }
});
DEMO
Source
Demo
jQuery.fn.selectText = function () {
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$(".edit").click(function () {
$(".edit-section").selectText();
});
from : Selecting text in an element (akin to highlighting with your mouse)
Possible duplicate - Programmatically select text in a contenteditable HTML element?
Copied following function from the answer.
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
var el = document.getElementById("foo");
selectElementContents(el);
Updated JS-Fiddle - http://jsfiddle.net/vishwanatharondekar/zSwBL/5/
Try
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$("button").click(function() {
$("#editable").selectText();
});
JSFiddle
Refence: How to select all text in contenteditable div?
I currently have a content editable div which I use as an editor but I'm looking to strip html (not including <br> tags) on paste.
At the moment I have another div <div class="hiddendiv common editor"></div> this one which collects all text and data added to the contenteditable div in order to determine height of the contenteditable div.
I've become confused and unsure how I will do this.
My Question is: How do I strip html formatting (not including <br> tags) whilst inserting text at the cursor caret on paste with jQuery?
HTML:
<div contenteditable='true' id="textarea" class="editor plain-box large-box textarea text common text-content-input quicksand color-dark-grey" data-text="Start typing..."></div>
<div class="hiddendiv common editor"></div>
jQuery
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
document.selection.createRange().pasteHTML(html);
}
}
$('#textarea').on("paste", function() {
var textarea = $('#textarea').html();
var hidden_div = $('.hiddendiv').html(textarea);
var plain_text = hidden_div.text();
$('#textarea').pasteHtmlAtCaret(plain_text);
});
var txt = $('#textarea'),
hiddenDiv = $(document.createElement('div')),
content = null;
txt.addClass('txtstuff');
hiddenDiv.addClass('hiddendiv common editor');
$('body').append(hiddenDiv);
txt.on('keyup input propertychange', function () {
content = $(this).html();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content + '<br>');
$(this).css('height', hiddenDiv.height());
});
This may be what you’re looking for:
<div contenteditable="plaintext-only" id="textarea" data-text="Start typing..."></div>
I have added a button to insert some text from a textarea to an editable DIV using this function found on stakoverflow.
function insertAtCursor(){
document.getElementById('myInstance1').focus() ; // DIV with cursor is 'myInstance1' (Editable DIV)
var sel, range, html;
var text = document.getElementById('AreaInsert').value ; // Textarea containing the text to add to the myInstance1 DIV
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode( document.createTextNode(text) );
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}
With Internet Explorer using document.selection.createRange().text it works fine for line breaks.
With Firefox and Chrome, line breaks of the textarea are not respected, all the text inserted to the editable div from the textarea is on only one line.
How to modify insertAtCursor() to make it works for line breaks with Firefox and Chrome ?
I suggest splitting the text up into separate text nodes, replacing the line breaks with <br> elements, creating a DocumentFragment containing the text and <br> nodes and calling insertNode() to insert it.
Demo: http://jsfiddle.net/timdown/zfggy/
Code:
function insertAtCursor(){
document.getElementById('myInstance1').focus() ; // DIV with cursor is 'myInstance1' (Editable DIV)
var sel, range;
var text = document.getElementById('AreaInsert').value ; // Textarea containing the text to add to the myInstance1 DIV
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var lines = text.replace("\r\n", "\n").split("\n");
var frag = document.createDocumentFragment();
for (var i = 0, len = lines.length; i < len; ++i) {
if (i > 0) {
frag.appendChild( document.createElement("br") );
}
frag.appendChild( document.createTextNode(lines[i]) );
}
range.insertNode(frag);
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().text = text;
}
}
I think I found a more appropriate solution for your problem. For demonstration see this Fiddle. See also the css property word-wrap.
Java Script:
var button = document.getElementById('insertText');
button.onclick = function() {
var text = document.getElementById('textarea').value;
document.getElementById('insertHere').innerText = document.getElementById('insertHere').textContent = text
};
To achieve cross browser compatibility, you could also do this:
var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
if (! isIE) {
HTMLElement.prototype.__defineGetter__("innerText",
function () { return(this.textContent); });
HTMLElement.prototype.__defineSetter__("innerText",
function (txt) { this.textContent = txt; });
}