Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  179] [ 7]  / answers: 1 / hits: 25660  / 9 Years ago, fri, december 4, 2015, 12:00:00

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;
}

More From » jquery

 Answers
104

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:




[#64161] Wednesday, December 2, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
adam

Total Points: 363
Total Questions: 102
Total Answers: 104

Location: Burkina Faso
Member since Thu, Dec 15, 2022
1 Year ago
;