0

Making a text editor that allows you to upload an image, and then it adds the image url and img tag to the content editable div.

I have everything working with this snippet...

function insertTextAtCursor(text) {
    var sel, range, html;
    sel = window.getSelection();
    range = sel.getRangeAt(0);
    range.deleteContents();
    var textNode = document.createTextNode(text);
    range.insertNode(textNode);
    range.setStartAfter(textNode);
    sel.removeAllRanges();
    sel.addRange(range);
}

...but it outputs the html string so I see "<img src=""/>" instead of the actual image.

Is there any way I can do this?

I have a response from my AJAX call where I use the function:

this.on("success", function(file, response) {
    var imageUrl = "https://s3-eu-west-1.amazonaws.com/mys3account/images/" + response.image['name'];
    insertTextAtCursor("<img src='" + imageUrl + "'/>");
});

Thanks.

zer00ne
  • 41,936
  • 6
  • 41
  • 68
Lovelock
  • 7,689
  • 19
  • 86
  • 186

1 Answers1

0

This solved it for me:

var descriptionNode = document.createElement("img");
descriptionNode.className = "img";
descriptionNode.src = text;

range.insertNode(descriptionNode);
range.setStartAfter(descriptionNode);

Taken from here: https://stackoverflow.com/a/8031639/2921557

Community
  • 1
  • 1
Lovelock
  • 7,689
  • 19
  • 86
  • 186