I'm trying to insert image to editable div. First time is working fine but after user change album (by choose select option) it doesnt work anymore.
The problem is when user 'click' select option it is change (window.getSelection()). I'm solving this problem by trying to clone getSelection object for using when we need it.
So any way to clone window.getSelection() objects?
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{
}
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(image);
}
A Naive cloning would be:
const cloneSelection = (sel = document.getSelection()) => {
const cloned = {}
for (const p in sel)
cloned[p] = sel[p]
return cloned
}
If you need to clone the range
, then do:
const clonedSelection = cloneSelection()
const clonedRange = selection.getRangeAt(0).cloneRange()
clonedSelection.addRange(clonedRange)
But you'll have to access it by selection.getRangeAt(1)
since it's been added after the initial one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With