jquery - How to get the current line position in the contenteditable div using javascript on keypress -


this question has answer here:

i creating customize editor using contenteditable div, need javascript code calculate line position of current caret position on keypress event. please make sure should work when add new line or remove line.

this contenteditable div format

<div contenteditable="true" id="editor">   <b>heading</b>   <br/>   line 1   <br/>   line 2   <br/>   line 3   <br/>   line 4   <br/>   line 5 </div> 

please see fiddle:

use <pre> instead.

html

<pre  contenteditable="true" id="editor"> line 1 line 2 line 3 line 4 line 5</pre>  <input id="addbtn" type="button" value="add line"/>  

javascript

$('#editor').on("mouseup", function getpos() {     var sel = document.getselection(),         nd = sel.anchornode,         text = nd.textcontent.slice(0, sel.focusoffset);      var linenum=text.split("\n").length;     alert(linenum); });  $('#addbtn').click(function(){    var str = "new line";    elem = document.getelementbyid("editor");    elem.innerhtml =  elem.innerhtml +"\n" + str;         }); 

i've updated jsfiddle, , used pre instead <br/> (for line breaks) fiddle


Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

Making Empty C++ Project: General exception (Exception from HRESULT:0x80131500) Visual Studio Community 2015 -

How to fix java warning for "The value of the local variable is not used " -