Insert image into "contenteditable" div using popup

I have an insert image button that pops up. I have this popup, the user can send the image to the server using PHP. When the transfer is successful, I get a page with INPUT TEXT. The os value of this INPUT is the name of the submitted file (for example: image.jpg).

Here is my problem. I would like to insert this image.jpg into my contentEditable div (window with mother).

And I would like to save the image in the same place where the mouse cursor was.

I found one example here. But when my image code is included in the div, it displays as text. Not like an html tag ... So I only get text, not an image!

Here is what I got.

SCRIPT:

function isOrContainsNode(ancestor, descendant) { var node = descendant; while (node) { if (node === ancestor) { return true; } node = node.parentNode; } return false; } function insertNodeOverSelection(node, containerNode) { var sel, range, html, str; if (window.getSelection) { sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { range = sel.getRangeAt(0); if (isOrContainsNode(containerNode, range.commonAncestorContainer)) { range.deleteContents(); range.insertNode(node); } else { containerNode.appendChild(node); } } } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); if (isOrContainsNode(containerNode, range.parentElement())) { html = (node.nodeType == 3) ? node.data : node.outerHTML; range.pasteHTML(html); } else { containerNode.appendChild(node); } } } 

A TYPE

 #editable { width:100%; height:100px; border:1px solid black; } #oculta { width:100%; height:30px; border:1px solid black; display:none; } 

HTML

 <div contenteditable="true" id="editable"> </div> <div id="oculta"> <form name="form"> &nbsp;<textarea name="area" rows="2" name="S1" cols="20"></textarea> <input type="button" onmousedown="insertNodeOverSelection(document.createTextNode(form.area.value), document.getElementById('editable'));" value="insert"></form> </div> <input type="button" onmousedown="document.getElementById('oculta').style.display='block';" value="test"> 

Thanks a lot!

+6
source share
1 answer

Can you get the text / file name correctly? Can you return the PATH to the downloaded file? If so, all you have to do is dynamically create the img tag and change its "src" attribute to the file path.

change โ†’ insertNodeOverSelection(document.createTextNode(form.area.value), document.getElementById('editable')); to

 var x=document.createElement('img'); x.src=form.area.value; insertNodeOverSelection(x, document.getElementById('editable')); 
+6
source

Source: https://habr.com/ru/post/908256/


All Articles