Amanjot
Amanjot

Reputation: 2058

Insert emoji at cursor

I already asked this question earlier on stack overflow but didnot get a answer. I have 2 links called add emoji 1 and add emoji 2. This was my ealier question. Insert smiley at cursor position

Now, even when I had made certain changes and the here the problem is that smileys only insert at the end of the div and not at the cursor position. My new demo is at: 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 smiley to insert in the respective contenteditable div where ever the cursor is. Thanks in advance.

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

Upvotes: 6

Views: 2893

Answers (2)

Muhammad Atif
Muhammad Atif

Reputation: 1102

I have tested this code for textbox with id txtUserName.Its working as you want

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

Upvotes: 1

Amit Chhangani
Amit Chhangani

Reputation: 28

Please find below lines of code which will resolve your query.

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 it is a possible duplicate of Insert text into textarea at cursor position (Javascript)

Please review the above link for the details

Upvotes: 0

Related Questions