4

I have a contentEditable div and a list of emojies images. What I am trying to do is that when a user click on an image, the image tag should be inserted at the cursor position.

I tired to do this but this code only insert the image at the end of the div which is not the case for me

$("#editable").append($(this).id); // $(this) is the image tag

How can I fix my problem? jsfiddle : http://jsfiddle.net/7VNTn/

Sora
  • 2,465
  • 18
  • 73
  • 146

3 Answers3

8

try this code , change "IMAGE URL" with any image url

var image = '<p><img src="IMAGE URL" ></p>';

var sel, range, node;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(image);
            range.insertNode(node);
          }
   } else if (document.selection && document.selection.createRange) {
               document.selection.createRange().pasteHTML(image);
   }
Khaled Hasania
  • 335
  • 6
  • 14
-2

Use following code.

        $("#editable").html($(this).id);

append method adds the element after your editable tag.So html method will put image inside youe row.try this

Chetan
  • 944
  • 5
  • 22
-2

Try this code

$(document).ready(function(){

    $("#image1").click(function(){
    $("#editable").prepend($(this));
    });


});

I used prepend instead of append since you want the image to appear before the text.

a_miguel6687
  • 521
  • 3
  • 10
  • 22