6

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.

Community
  • 1
  • 1
Amanjot Kaur
  • 2,028
  • 4
  • 18
  • 33

2 Answers2

1

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);
    });
m4n0
  • 29,823
  • 27
  • 76
  • 89
Muhammad Atif
  • 1,050
  • 1
  • 9
  • 21
0

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

Community
  • 1
  • 1
  • 1
    From where to find myField, myValue - the parameters of the function @Amit Chhangani – Amanjot Kaur Jul 28 '15 at 07:04
  • 1
    or what is sel? this answer is lacking fullness – sertsedat Jul 28 '15 at 07:10
  • myField is the "div" in which you have to insert the emoji, and myValue is the link of the emoji to insert. And for details please follow the link. It will work in the same manner as it works with textarea. – Amit Chhangani Jul 28 '15 at 07:29
  • Does this code works for contenteditable div @Amit Chhangani . I had tried it and its not working. and also I want to add image , not text – Amanjot Kaur Jul 28 '15 at 07:31