Paste emoji into cursor

I already asked this question before when stack overflowed, but received no answer. I have 2 links called add emoji 1 and add emoji 2. That was my question. Paste emoticon at cursor position

Now, even when I made certain changes, and here the problem is that emoticons are inserted only at the end of the div, and not at the cursor position. My new demo: https://jsfiddle.net/ftwbx88p/8/

$( document ).on( "click" , "#button" , function() { $( ".editable.focus" ).append( '<img src="https://cdn.okccdn.com/media/img/emojis/apple/1F60C.png"/>' ); }); 

I want the emoticon to be inserted into the corresponding contenteditable div, wherever the cursor is. Thanks in advance.

Note: I had a contenteditable div where I want to add image and not in the textarea.

+4
source share
2 answers

Below you will find lines of code that will resolve your request.

 function insertAtCursor(myField, myValue) { //IE support if (document.selection) { myField.focus(); sel = document.selection.createRange(); sel.text = myValue; } //MOZILLA and others else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); } else { myField.value += myValue; } } 

And this is a possible duplicate. Insert text into the text box at the cursor position (Javascript)

Read the link above for details

0
source

I tested this code for a text field with id txtUserName.Its working as you want

The code:

 $(document).on("click", "#button1", function () { var cursorPosition = $("#txtUserName")[0].selectionStart; var FirstPart = $("#txtUserName").val().substring(0, cursorPosition); var NewText = " New text "; var SecondPart = $("#txtUserName").val().substring(cursorPosition + 1, $("#txtUserName").val().length); $("#txtUserName").val(FirstPart+NewText+SecondPart); }); 
0
source

All Articles