1

I'm using a div with contenteditable as a textarea, so I can insert PNG emoji. Now everything works fine except for when I want to insert the emoji in the current caret position. I only know .append() which simply inserts the emoji at the end of the text. this is my code:

<div id="message-field" class="form-control message-field" contenteditable="true"></div>



<span class="em em-1F3C6" data-em="1F3C6"></span>
<span class="em em-1F6AB" data-em="1F6AB"></span>
<span class="em em-1F44D" data-em="1F44D"></span>
<span class="em em-1F44E" data-em="1F44E"></span>



$('.em').click(function() {
    var em = $(this).data('em');
    $('#message-field').append('<img src="_/css/img/emoji/' + em + '.png">&nbsp;');
});

Now how to make it insert the emoji in the current caret position and not in the end?

Thanks!

medk
  • 9,233
  • 18
  • 57
  • 79
  • you're probably going to have to wrap each character in its own span, then set up event listeners on them to detect which character your mouse is over, then use that information to correctly insert the emoji. **Edit:** actually, so that you don't have to set up a ton of event listeners, you can probably inspect the event object of the click event to see the elements the mouse was over when you clicked, check if one of them was a span in your editor, and if it is, insert the emoji appropriately. – Mason Apr 12 '20 at 02:18
  • It's gonna be a big mess. Thanks anyway :) – medk Apr 12 '20 at 02:22
  • https://stackoverflow.com/questions/2920150/insert-text-at-cursor-in-a-content-editable-div should be exact solution you want @medk – artgb Apr 12 '20 at 02:58
  • @artgb sorry you didn't get the point, that solution is for inserting something exactely in the position of the cursor when clicked, for me, I'm talking about the position of the cursor in the editable div that is used as a textarea. Sorry it's my fault, I mean the position of the caret not the cursor. – medk Apr 12 '20 at 03:16
  • 1
    I just thought you look for something like https://jsfiddle.net/Xeoncross/4tUDk/ which is answered in https://stackoverflow.com/questions/2920150/insert-text-at-cursor-in-a-content-editable-div – artgb Apr 12 '20 at 03:37
  • @artgb Yes I think this is it, I'll try and tell you. Thanks! – medk Apr 12 '20 at 12:36
  • @artgb This is it, but when I put it in my script it works but always puts in the beginning. – medk Apr 12 '20 at 12:49
  • In that case, you can just share jsfiddle which is not working – artgb Apr 12 '20 at 12:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/211473/discussion-between-medk-and-artgb). – medk Apr 12 '20 at 13:15

0 Answers0