Behaviour Of Enter Key In Contenteditable Div - javascript

I'm trying to make a rich text editor and i have near to my success. I'm trying to change the behaviour of enter key in contenteditable div because when pressing enter firefox produced <br> thats ok but Chrome and IE produced a <p> and <div> here i'm trying to force all browser to produce <br> when press enter under <div contenteditable="true"></div>. Everything working fine in internet explorer but in all browsers would have to press enter two times for new line or <br>.
Here is my code.
<!doctype html>
<html>
<head>
<title>Rich Text Editor</title>
<script type="text/javascript">
function preview() {
var textbox = document.getElementById('textBox');
document.getElementById("view").innerHTML=textbox.innerHTML;
}
function enterKeyPressHandler(evt) {
var sel, range, br, addedBr = false;
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
if (charCode == 13) {
if (typeof window.getSelection != "undefined") {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
br = document.createElement("br");
range.insertNode(br);
range.setEndAfter(br);
range.setStartAfter(br);
sel.removeAllRanges();
sel.addRange(range);
addedBr = true;
}
} else if (typeof document.selection != "undefined") {
sel = document.selection;
if (sel.createRange) {
range = sel.createRange();
range.pasteHTML("<br>");
range.select();
addedBr = true;
}
}
// If successful, prevent the browser's default handling of the keypress
if (addedBr) {
if (typeof evt.preventDefault != "undefined") {
evt.preventDefault();
} else {
evt.returnValue = false;
}
}
}
}
function onload(){
var el = document.getElementById("textBox");
if (typeof el.addEventListener != "undefined")
{
el.addEventListener("keypress", enterKeyPressHandler , false);
}
else if (typeof el.attachEvent != "undefined")
{
el.attachEvent("onkeypress", enterKeyPressHandler);
}
}
</script>
</head>
<body onload="javascript:onload();">
<form name="myform" method="POST">
<div id="textBox" contenteditable="true" style="width:500px; height:150px; padding:20px; border:solid thin #000"></div>
</form>
<br>
<div id="view" style="width:500px; height:150px; padding:20px; border:solid thin #000"></div>
<br>
<button onClick="javascript:preview();">Preview</button>
</body>
</html
Demo JSFiddle

My solution is to handle an enter button. Different options for different tags. Look at https://codepen.io/MaratKh/pen/oKXxvV
const ed = document.getElementById('editable'),
ta = document.getElementById('txt');
const key13 = function(ev){
if(ev.keyCode==13) {
ev.preventDefault();
const selection = window.getSelection(),
range = selection.getRangeAt(0),
node = document.getSelection().anchorNode,
pNode = node.parentNode;
var tag = pNode.nodeName.toUpperCase();
switch(tag) {
case 'P':
tag = 'BR';
break;
case 'DIV':
tag = 'p';
break;
case 'SPAN':
tag = 'span';
break;
case 'BR':
tag = NULL;
break;
default:
tag = 'BR';
}
const el = document.createElement( tag );
range.deleteContents();
range.insertNode(el);
if ('BR'===tag) {
range.setStartAfter(el);
range.setEndAfter(el);
} else {
range.setStart(el, 0);
range.setEnd(el, 0);
}
const ze = document.createTextNode("\u200B");
range.insertNode(ze);
range.setStartBefore(ze);
range.setEndBefore(ze);
selection.removeAllRanges();
selection.addRange(range);
ev.stopPropagation();
}
ta.value = ed.innerHTML;
}
ed.addEventListener( 'keydown', key13, false);
.xrow {
display: block;
display: flex;
flex-direction: row;
align-items: stretch;
justify-content: space-between;
}
.xrow .col {
display: block;
flex: 1;
}
.xrow .col:first-child{
border-right:#669 1px dashed;
margin-right:20px;
}
textarea {
width:100%;
height:300px;
}
#editable{
padding:16px 9px;
border: 2px dashed #ddc;
}
<div class="xrow">
<div class="col">
<h3>Editable</h3>
<div id="editable" contenteditable="true">
<h1>Hi</h1>
<div>div</div>
<p>p</p>
text
</div>
</div>
<div class="col">
<h3>Result</h3>
<textarea id="txt"></textarea>
</div>
</div>

IT WORKS!!!
if (window.getSelection) {
var selection = window.getSelection(),
range = selection.getRangeAt(0),
br = document.createElement("br");
range.deleteContents();
range.insertNode(br);
var newLine=document.createTextNode('\n');
range.setStartAfter(br);
range.setEndAfter(br);
range.insertNode(newLine);
selection.removeAllRanges();
selection.addRange(range);
}

Related

Get and set cursor position with contenteditable div

I have a contenteditable div which I would like to be able to have users insert things such as links, images or YouTube videos. At the moment this is what I have:
function addLink() {
var link = $('#url').val();
$('#editor').focus();
document.execCommand('createLink', false, link);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Text Editor -->
<div id="editor" contenteditable="true"></div>
<!-- Add Link -->
<input type="text" id="url">
<button onclick="addLink()">Submit</button>
As you can see, the user has to type into a separate text box to enter the link address. As a result, when the link is added to the editor, it is not added to the position that the pointer/caret was on.
My question is how I can get and set the location of the pointer/caret. I have seen other questions such as this for setting the pointer however I would prefer to have a solution which is supported in all modern browsers, including Chrome, Safari, Firefox and IE9+.
Any ideas? Thanks.
Edit:
I found the code below which gets the position however, it only gets the position according to the line it is on. For example if I had this (where | is the cursor):
This is some text
And som|e more text
Then I would be returned the value 7, not 24.
function getPosition() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
return sel.getRangeAt(0).startOffset;
}
}
return null;
}
There's a ton of related info onsite. This one works for me and my clients.
DEMO
https://stackoverflow.com/a/6249440/2813224
function setCaret(line, col) {
var ele = document.getElementById("editable");
var rng = document.createRange();
var sel = window.getSelection();
rng.setStart(ele.childNodes[line], col);
rng.collapse(true);
sel.removeAllRanges();
sel.addRange(rng);
ele.focus();
}
//https://stackoverflow.com/a/6249440/2813224
var line = document.getElementById('ln').value;
var col = document.getElementById('cl').value;
var btn = document.getElementById('btn');
btn.addEventListener('click', function(event) {
var lineSet = parseInt(line, 10);
var colSet = parseInt(col, 10);
setCaret(lineSet, colSet);
}, true);
<div id="editable" contenteditable="true">
<br/>text text text text text text
<br/>text text text text text text
<br/>text text text text text text
<br/>
<br/>
</div>
<fieldset>
<button id="btn">focus</button>
<input type="button" class="fontStyle" onclick="document.execCommand('italic',false,null);" value="I" title="Italicize Highlighted Text">
<input type="button" class="fontStyle" onclick="document.execCommand('bold',false,null);" value="B" title="Bold Highlighted Text">
<input id="ln" placeholder="Line#" />
<input id="cl" placeholder="Column#" />
</fieldset>
A good rich-text editor is one of the harder things to do currently, and is pretty much a project by itself (unfriendly API, huge number of corner cases, cross-browser differences, the list goes on). I would strongly advise you to try and find an existing solution.
Some libraries that can be used include:
Quill (http://quilljs.com)
WYSGIHTML (http://wysihtml.com)
CodeMirror library (http://codemirror.net)
I have tried to find a solution,
With a little help it can be perfected.
It is a combination of answers I've found on SO, and my exp.
Its tricky, its messy... but if you must, you can use it but it requires a bit of work to support inner links (if you cursor is on an anchor it will create anchor inside anchor)
Here's the JS:
var lastPos;
var curNode = 0;
function setCaret() {
curNode=0;
var el = document.getElementById("editor");
var range = document.createRange();
var sel = window.getSelection();
console.log(el.childNodes);
if (el.childNodes.length > 0) {
while (lastPos > el.childNodes[curNode].childNodes[0].textContent.length) {
lastPos = lastPos - el.childNodes[curNode].childNodes[0].textContent.length;
curNode++;
}
range.setStart(el.childNodes[curNode].childNodes[0], lastPos);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
el.focus();
};
function savePos() {
lastPos = getCaretCharacterOffsetWithin(document.getElementById('editor'));
}
function addLink() {
console.log(lastPos);
setCaret();
console.log(getCaretCharacterOffsetWithin(document.getElementById('editor')));
console.log('focus');
// $("#editor").focus();
var link = $('#url').val();
document.execCommand('createLink', false, link);
}
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ((sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
fiddle
This is what you asked for, in your bounty: on the following example you can see how to detect the exact number of characters of the actual point where you clicked the mouse on:
<!-- Text Editor -->
<div id="editor" class="divClass" contenteditable="true">type here some text</div>
<script>
document.getElementById("editor").addEventListener("mouseup", function(key) {
alert(getCaretCharacterOffsetWithin(document.getElementById("editor")));
}, false);
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
</script>
I found a problem with emojis. Emojis have a length which is more than 1.
I solved it.
<script>
function getCursorPosition() {
if(window.getSelection()){
var sel = window.getSelection();
if(sel.getRangeAt){
var pos = sel.getRangeAt(0).startOffset;
var endPos = pos + Array.from(editor.innerHTML.slice(0,pos)).length - editor.innerHTML.slice(0,pos).split("").length;
return endPos;
}
}
return null;
}
var editor = document.querySelector("#editor");
var output = document.querySelector("#output");
editor.addEventListener("input",function(){
output.innerHTML = "Selection: " + getCursorPosition();
});
</script>
<div contenteditable id="editor">text</div>
<div id="output">Selection:</div>

copy whole html table to clipboard javascript

I have write javascript to select the table but I want to now automaticaly copy it after the click of the button.Please help me.My javascript is like this.
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
document.execCommand('Copy');
} catch (e) {
range.selectNode(el);
sel.addRange(range);
document.execCommand('Copy');
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
range.execCommand('Copy');
}
}
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
document.execCommand("Copy");}
Try this:
<script type="text/javascript">
function copytable(el) {
var urlField = document.getElementById(el)
var range = document.createRange()
range.selectNode(urlField)
window.getSelection().addRange(range)
document.execCommand('copy')
}
</script>
<input type=button value="Copy to Clipboard" onClick="copytable('stats')">
<table id=stats>
<tr>
<td>hello</td>
</tr>
</table>
This has worked for me, it is not only restricted to table, but it can even select and copy to clipboard all elements inside Node specified with id.
I have tested in Mac Chrome as well as windows chrome.
Usescase : Copy Signature created by Signature Generator based on JS
Demo :
<div id="signature_container">
<p id="company_name" style="margin-top: 4px; margin-bottom: 0px; color: #522e64; font-weight: 700; font-size: 16px; letter-spacing: 1px; border-bottom: solid 2px #522e64; width:250px; padding-bottom: 3px;">The Company Name</p>
<p style="margin-top: 4px; margin-bottom: 0px; color: #00706a; font-weight: 700; font-size: 15px;"> <span id="first_name_output_2"></span>Firstname<span id="last_name_output_2"> Lastname</span> <span id="designation_output_2" style="color: #000000; font-weight: 500; font-size: 15px;">Designation</span></p>
<p style="margin-top: 0px; margin-bottom: 0px; color: #625469; font-weight: normal; font-size: 15px; letter-spacing: 0.6px;">youreamil#xyz.com<span id="email_output_2"></span> </p>
</div>
<br><br>
<input type="button" onclick="selectElementContents( document.getElementById('signature_container') );" value="Copy to Clipboard">
<script>
function selectElementContents(el) {
var body = document.body,
range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
range.selectNodeContents(el);
sel.addRange(range);
}
document.execCommand("Copy");
}
</script>
I know this is an old one, but if any one still looking for a solution. this one worked for me
<script>
$(document).ready(function() {
$("#copyBtn").on("click",
function(e) {
copyTable("listTable", e);
});
});
function copyTable(el, e) {
e.preventDefault();
var table = document.getElementById(el);
if (navigator.clipboard) {
var text = table.innerText.trim();
navigator.clipboard.writeText(text).catch(function () { });
}
}
</script>
The previous scripts did not work for me because the .execCommand("Copy") was not triggering. By attaching it to the document itself, and moving it outside of the conditional, I was able to get it to work:
I think this function is more robust:
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
document.execCommand("Copy");
}
UPDATE
Use this code instead.
Code:
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
document.execCommand("copy");
}
}
<input type="button" value="select table"
onclick="selectElementContents( document.getElementById('table') );">
<table id="table">
<thead>
<tr><th>Heading</th><th>Heading</th></tr>
</thead>
<tbody>
<tr><td>cell</td><td>cell</td></tr>
</tbody>
</table>
by using a library called clipboard.js making it much easier.
for more info, check: https://webdesign.tutsplus.com/tutorials/copy-to-clipboard-made-easy-with-clipboardjs--cms-25086
<script src="//cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.4.0/clipboard.min.js">
(function(){
new Clipboard('#copy-table-button');
})();
</script>
<button class="btn" id="copy-table-button" data-clipboard-target="#table_results">Copy</button>
<table id='table_results' >
</table>
You can use this custom script, if you need to copy to clipboard all data from table;
html:
<button class='btnclipboard' data-source='tableStudents'> Copy table </button>
<table id="tableStudents">
<thead>
<th> user_id </th>
<th> Name </th>
</thead>
<tbody>
<tr>
<td> 123 </td>
<td> Proba </td>
</tr>
<tbody>
</table>
<script>
$('.btnclipboard').click(function(e) {
e.preventDefault();
copyTableToClipboard($(this).data('source'));
});
function copyTableToClipboard() {
var clipboard=new Clipboard('.btnclipboard',{
text: function(trigger) {
var txt=[];
var headColumns = [];
$("#tableStudents th").each(function(){
var textColumn = $(this).text();
if(textColumn == null || textColumn == "") {
textColumn = $(this).attr('title');
}
if(textColumn == undefined || textColumn == null) {
textColumn = "";
}
headColumns.push(textColumn);
// console.log($(this).text());
});
console.log('headColumns', headColumns);
var head=headColumns;
txt.push(head.join("\t"));
var rowColumns=[];
$("#tableStudents tr").each(function(){
var row=[];
$(this).find('td').each(function(){
var textColumn = $(this).text();
if($(this).find("i").hasClass('fa-check')){
textColumn = "1";
}
// if(textColumn == "") {
// // textColumn = $(this).attr('title');
// textColumn = "";
// }
// if(textColumn != null) {
row.push(textColumn);
// }
//console.log($(this).text());
});
if(row.length > 0) {
rowColumns.push(row);
txt.push(row.join("\t"));
}
});
console.log('rowColumns', rowColumns);
return txt.join("\n");
}
});
clipboard.on('success', function(e) {
console.info('Action:', e.action);
e.clearSelection();
if (Notification.permission == "granted")
{
var notification = new Notification('Data copied to clipboard', {
icon: '../dist/img/favicon.png',
body: "You can now paste (Ctrl+v) into your favorite spreadsheet editor !"
});
}else{
console.warn(Notification.permission);
}
});
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
}
</script>
After you click on the button, your table data should be copied.
All answers using execCommand are deprecated.
The correct answer is using Clipboard API, as described by user Craig Walker in an answer to this question, above. Click here to go to the answer.
OP, please update this post and mark Craig's answer as correct.
function selectElementContents(el) {
var body = document.body, range, sel;
if (document.createRange && window.getSelection) {
range = document.createRange();
sel = window.getSelection();
sel.removeAllRanges();
try {
range.selectNodeContents(el);
sel.addRange(range);
} catch (e) {
range.selectNode(el);
sel.addRange(range);
}
} else if (body.createTextRange) {
range = body.createTextRange();
range.moveToElementText(el);
range.select();
}
CopiedTxt = document.selection.createRange();
CopiedTxt.execCommand("Copy");}

how to get caret position in textarea

JS
function doGetCaretPosition (ctrl)
{
var CaretPos = 0;
// IE Support
if (document.selection)
{
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
{
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
window.onload=function(){
editor = CKEDITOR.replace('content');
}
HTML:
<body>
<form name="inForm" method="post">
<textarea id="content" name="content" cols="100%" rows="10">1234dfgdf5</textarea>
<br>
<input type="button" onclick="alert(doGetCaretPosition(document.getElementById('content')));"
value="Get Position">
</form>
</body>
Why "Get Position" and click it to continue zeros is coming?

How to show markup color code in my phpbb BBCode

I have default [code] [/code] BBCode on my phpbb forum. But it does not show the color for code's markup. I want to see the exact color for every php, html, css color etc color.
I used bellows code there to create BBCode.
HTML Replacement :
<script type="text/javascript">
// select all function
function selectCode(a)
{
// Get ID of code block
var e = a.parentNode.parentNode.getElementsByTagName('CODE')[0];
// Not IE and IE9+
if (window.getSelection)
{
var s = window.getSelection();
// Safari
if (s.setBaseAndExtent)
{
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}
// Firefox and Opera
else
{
// workaround for bug # 42885
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<BR>')
{
e.innerHTML = e.innerHTML + ' ';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}
// Some older browsers
else if (document.getSelection)
{
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
// IE
else if (document.selection)
{
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}
//expand - collapse settings
function expandcollapse(a) {
var ee = a.parentNode.parentNode.getElementsByTagName('dd')[0];
if (ee.style.maxHeight == '200px')
{
ee.style.maxHeight = '2000px';
a.innerHTML = 'collapse';
}
else {
ee.style.maxHeight = '200px';
a.innerHTML = 'expand';
};
}
</script>
<![if !IE]>
<script type="text/javascript">
function scrolltest(k) {
var eee = k.getElementsByTagName('dd')[0];
var old = eee.scrollTop;
eee.scrollTop += 1;
if (eee.scrollTop > old) {
eee.scrollTop -= 1;
k.getElementsByTagName('a')[1].style.visibility = "visible";
}
}
</script>
<![endif]>
<div class="pre" onmouseover="scrolltest(this); return false;">
<dt class="pre_header">
<b>Code: </b>
Select all
<a style="float:right; visibility:hidden;" href="#" onclick="expandcollapse(this); return false;">expand</a>
</dt>
<dd style="max-height:200px; overflow:auto;">
<code>
{TEXT}
</code>
</dd>
</div>
If you're looking for a syntax highlighter, check out this phpbb plugin/mod:
http://sourceforge.net/projects/geshi-phpbb/
Read GeSHi for more.

Highlight Text in Text Field at a Specific Point

I'm trying to replicate Twitter's "compose new tweet" box. I have a counter that shows how many letters you have left. I'm not using HTML's maxlength, so when you go into the negatives, the counter turns red and is negative. In Twitter, your overflowed text is highlighted a light red.
How would I manage to highlight overflowed text in a text field? Here's my HTML and JavaScript that I already have. (I've attempted to highlight the text before but I didn't know where to start 'cuz I'm a noob. :P ):
<div id="char_count">
<span id="charsLeftH" title="Characters Remaining" style="cursor: pointer">500</span>
</div>
<input type="button" value="Send" id="submit">
<script>
var chars = 500;
function charsLeft() {
chars = 500 - $("#type_area").val().length;
document.getElementById("charsLeftH").innerHTML=chars;
if (chars < 50 && chars > 0) {
document.getElementById("charsLeftH").style.color="#9A9A00";
document.getElementById("submitX").id="submit";
} else if (chars < 1) {
document.getElementById("charsLeftH").style.color="#BD2031";
if (chars < 0) {document.getElementById("submit").id="submitX";}
} else {
document.getElementById("charsLeftH").style.color="#000000";
document.getElementById("submitX").id="submit";
}
};
charsLeft();
</script>
here is the script
jfiddle:
style:
<style type="text/css">
.red{
color:#F00;
}
#mytextarea{
background-color:#999;
filter:alpha(opacity=50);
opacity:0.5;
border: 1px #3399FF solid;
min-height:50px;
width:150px;
word-wrap:break-word;
}
</style>
html:
<div contenteditable="true" id="mytextarea" onChange="charsLeft(this.innerHTML)" onKeyUp="charsLeft(this.innerHTML)"></div> <div id="remaining"></div>
javascript:
<script>
var before = 1;
var chars = 10;
var len = 0;
var div = document.getElementById('mytextarea');
var el = document.getElementById('remaining');
el.innerHTML = chars;
var overchars = 92; //length of the tags
function charsLeft(val) {
if (typeof (val) != 'undefined') {
val = val.replace('<font style="background-color:#F36;" id="reddragonred">', '');
val = val.replace('</font>', "");
len = val.length;
if (len > chars) {
plusvalor = val.slice(chars, len);
redstr = '<font style="background-color:#F36;" id="reddragonred">' + plusvalor + '</font>';
blackstr = val.slice(0, chars);
div.innerHTML = blackstr + redstr;
var subj = document.getElementById('reddragonred');
var cursorepos = subj.innerHTML.length;
var range = document.createRange();
var sel = window.getSelection();
console.log(before+' '+len);
if((before>0)&&(before<len)){
console.log('no');
try{
console.log(cursorepos);
if(cursorepos==0){
range.setStart(subj, 0);
}else{
range.setStart(subj, 1);
}
}catch (e){
console.log(e);
}
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
div.focus();
}
before=len;
}
}
el.innerHTML = chars - len;
}
</script>

Categories

Resources