Reputation: 2551
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/
Upvotes: 4
Views: 2791
Reputation: 345
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);
}
Upvotes: 8
Reputation: 529
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.
Upvotes: -2
Reputation: 942
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
Upvotes: -2