How to select all text in contenteditable div? - javascript

Before this is flagged as a duplicate, I want you to realize that no one has actually provided a good answer for this specific question. In select all text in contenteditable div when it focus/click, the accepted answer and Tim Down's answer are both not helpful, as they only work when the element is already focused. In my case, I want all the text in the contenteditable div to be selected after the click of a button, even if the div was not focused beforehand.
How could I do this?

I used some code from this thread to come up with my answer. It's 100% jQuery as you asked for as well. Hope you like it :)
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 link.

For example in next scenario if user set focus into editable div (with mouse, keyboard or by clicking a button) then content of editable div is selected.
<div id="editable" style=" border:solid 1px #D31444" contenteditable="true"
onfocus="document.execCommand('selectAll', false, null);">
12 some text...
</div>
<button onclick="document.getElementById('editable').focus();" >Click me</button>
On JSFiddle: http://jsfiddle.net/QKUZz/

Great function.
I've adapted it to enable full selection of text across any number of editable divs via a class, whether clicked directly, or tabbed to:
$.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);
}
};
$(".editable").on("focus", function () {
$(this).selectText();
});
$(".editable").on("click", function () {
$(this).selectText();
});
$('.editable').mouseup(function(e){
e.stopPropagation();
e.preventDefault();
// maximize browser compatability
e.returnValue = false;
e.cancelBubble = true;
return false;
});
HTML:
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">01 text...</div>
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">02 text...</div>
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">03 text...</div>
FIDDLE:
http://jsfiddle.net/tw9jwjbv/

Chrome does select everything, so I just added RAF to work around it:
requestAnimationFrame(() => document.execCommand('selectAll'));
Demo: http://jsfiddle.net/0aqptw8m/

<div id="test" style=" border:solid 1px #D31444" contenteditable="true" onclick="document.execCommand('selectAll',false,null)">12 some text...</div>
Judging by this answer provided in the link, cant you use the code on click within your button.
What im saying is even say in the div onfocus="document.execCommand('selectAll',false,null)"
Then use jQuery to trigger focus $('#test').focus();

Related

how can I move cursor at any position after editing text at paragraph contenteditable in js

I have contenteditable paragraph where I can write specific words which will automatically be colored . But when I try to edit already colored text my cursor position moves backward so how can I put my cursor at current position while editing already colored text.
my html code:-
<p contenteditable="true" id="ide" style="border:1px solid red;" >...</p>
my js code:-
<script>
function setEndOfContenteditable(contentEditableElement)
{
var range,selection;
if(document.createRange)
{
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}else if(document.selection){
range = document.body.createTextRange();
range.moveToElementText(contentEditableElement);
range.collapse(false);
range.select();
}
}
$(document).ready(function(){
$("#ide").bind('keyup',function(){
var x = $(this).text();
color(x)
setEndOfContenteditable(this);
});
});
function color(c){
var str = c;
var res = str.replace(/hello|house|car|happy/gi, function myFunction(x)
{
return '<span style="color:red;">'+x+'</span>';});
document.getElementById("ide").innerHTML = res;
}
Many people who try this can say this is correct but please try by typing hello or house or car or happy on contenteditable paragraph it will be automatically colored now go back to edit that colored string.
demo:- https://jsbin.com/nodome/edit?html,output
So, your question is a little bit misleading, your problem is keyup event on ⟵→ arrow keys or Select+All, after every keyup your function trying to detect word and execute color(), so if you use keypress event you can avoid this.
$("#ide").bind('keypress', function() {
var x = $(this).text();
color(x)
setEndOfContenteditable(this);
});
But if you want to execute color() after keyup you need to detect which key pressed and exclude arrow keys.
JSBin

Selecting text in a div programmatically and simultaneously by selecting same text in textarea

I have a div and there is a text in it.I want a part of that text to be selected programmatically according position value of characters.
<div id="textdiv">
Hello world. I am a friend.
</div>
I want "llo world" part to be selected(I mean highlighted/selected like making selection of content in an input/textarea ). In that case position values are first (3) and last (10).
But when i try select a part of text in textarea and get the same text selected in other div, it doesn' t select the same text, it selects from the beginning of text to the first position value which is "He" part in this case.
<body>
<div style="display:block;display:inline-block;float:left;border:1px solid green;">
<textarea id="textarea_" style="height:4em;width:200px;">Hello World! I am friend!</textarea>
</div>
<div id="otherdiv" style="border:1px solid black;display:inline-block;height:4em;width:200px;float:left;clear:left;">
Hello World! I am friend!
</div>
<script>
$(function(){
var otherdiv=document.getElementById('otherdiv');
var selectionafter ;
var selectionstart ;
var diff;
var range;
var endNode, startNode;
var textare=$('#textarea_');
var sel = document.getSelection();
textare.on('mousedown', function(event){
textare.on('mousemove', function(event){
selectionafter=event.target.selectionEnd;
selectionstart=event.target.selectionStart;
diff=selectionafter-selectionstart;
if(selectionafter!=0 && selectionstart!=0 && diff!=0){
endNode, startNode = endNode = otherdiv.firstChild;
startNode.nodeValue = startNode.nodeValue.trim();
range = document.createRange();
range.setStart(startNode, selectionstart);
range.setEnd(endNode, selectionafter+1);
sel.removeAllRanges();
sel.addRange(range);
}
});
});
});
</script>
</body>
jsFiddle
You should not do all that stuff inside a mousemove event handler.
Here is a corrected version that works using a select event handler:
jsFiddle

JavaScript - Select span text on mouse hover

I have this HTML code.
<div class="dontsplit" onmouseover="selCode('c111');">
Face savoring delicious food <span class="notranslate" id="c111">😊</span>
</div>
I want to select the value between span tags when mouse hovers the div. The code I am using is this.
function selCode(objId) {
if(document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(objId));
range.select();
} else if(window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(objId));
window.getSelection().addRange(range);
}
}
But it doesn't seem to work. How do I get this work?
I repeat. I need to automatically select the text between span when mouse hovers over the div. So it can be copied easily. Thanks in advance!
Your script is working for the first mouseover but the second one inwards is giving the error Discontiguous selection is not supported. so clear the existing selection before doing a new selection.
function selCode(objId) {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementById(objId));
range.select();
} else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementById(objId));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
}
}
Demo: Fiddle
I think this should help.
You can use jQuery .text() method.
You have a span with notranslate class.
So you can do somthing like this to get the text:
$(".notranslate").text();
http://jsfiddle.net/L8r6ns88/
Try this one. I'm using jquery to make this task done.
HTML
<div class="dontsplit">
Face savoring delicious food <span class="notranslate" id="c111">😊</span>
</div>
JS
$(function(){
$('.dontsplit').on('mouseover','.notranslate', function(){
console.log($(this).text()); //see result
})
})

Dragging a div select whole text

imagine i have a div
<div id="blah">
spotify:track:something
spotify:track:something
spotify:track:something
spotify:track:something
</div>
With close to 100+ of spotify:track stuff and I want to drag whole list to Spotify program to create a new playlist, but first I would have to select all the text.
Is it possible to make that starting to drag div automatically would select whole text.
For example: http://codepen.io/anon/pen/Hwbdy
It actually doesn't if it's a div or text area as long as a user can simple click and drag without selecting the text, thanks
if you want to select texts by javascript try this:
function select(){
var div = document.getElementById('blah'),
sel, range;
if(window.getSelection){
range = document.createRange();
range.selectNode(div)
sel = window.getSelection();
sel.addRange(range);
}else{
range = document.body.createTextRange();
range.moveToElementText(div);
range.select();
}
}
demo / jsfiddle
Maybe use jQuery? :
$("#yourID").focus(function() {
var $this = $(this);
$this.select();
// Work around Chrome's little problem
$this.mouseup(function() {
// Prevent further mouseup intervention
$this.unbind("mouseup");
return false;
});
});

Hidden text that can be dragged from the browser?

How can you create an html element that when dragged from the browser into a text editor, hidden text on or in the dragged element will be pasted into the editor?
My first thought was to use the href attribute on the anchor tag:
Drag me into a text editor!
This works great in chrome, but firefox and safari remove spaces from the href value which renders the copied message unusable.
Any ideas?
Instead of manipulating the browser's default behavior for dragging text/links/images, you want to set the data to something arbitrary in the dragstart event.
For example, use the text from a hidden #content:
$('[draggable]').on('dragstart', function(e) {
var content = $(this).find('#content').text(); // Can be anything you want!
e.originalEvent.dataTransfer.setData('text/plain', content);
$(this).addClass('dragging');
});
Here is a working JSFiddle
For versions of IE below 10 which don't support the dataTransfer method, I've discovered another somewhat hacky way to make this work.
Basically you make text invisible with css then use js to select it in the background on hover.
HTML
<div id="drag_area" draggable="true">
<div id="text">
hidden text
</div>
</div>​
CSS
#text { filter:alpha(opacity=0); opacity:0;
overflow:hidden; z-index:100000; width:180px; height:50px }
​
JS
function selectText(elementID) {
var text = document.getElementById(elementID);
if ($.browser.msie) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if ($.browser.mozilla || $.browser.opera) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
} else {
var selection = window.getSelection();
selection.setBaseAndExtent(text, 0, text, 1);
}
}
$('#drag_area').hover(function(){
selectText('text');
});
Here it is combined with Anson's solution and a little feature detection:
http://jsfiddle.net/zaqx/PB6XL/
(works in IE8, IE9 and all modern browsers)
EDIT: Updated Fiddle in the comments below.

Categories

Resources