4

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);

 }
pors
  • 191
  • 2
  • 3
  • 15
  • Sounds like an X/Y problem? The selection is lost when the focus goes to the "select option" instead, and you should probably just have stored the position in the range first, not the entire selection. – adeneo May 29 '16 at 12:05
  • i'm not sure with this but how can just keep X/Y position and use it in my code? In my code using 'sel = window.getSelection();' any advice please? – pors May 29 '16 at 12:11

2 Answers2

2

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.

vsync
  • 118,978
  • 58
  • 307
  • 400
0

You don't need to clone anything. Just set the last selected "editable" div to a variable. Like this:

let selectedDiv = null
document.addEventListener('selectionchange', () => {
  if(document.getSelection().focusNode.classList.contains("editable")){
    selectedDiv = document.getSelection().focusNode;
  }
});
const button = document.querySelector("button");
button.addEventListener('click', () => {
  selectedDiv.classList.toggle("highlight");
});
div {
  outline: 2px dashed blue;
  width: 96px;
  height: 96px;
  display: inline-block;
}
.highlight {
  background: yellow;
}
<h4>My Select Section</h4>
<section>
  <p>This is my select box</p>
  <select>
    <option>one</option>
    <option>two</option>
  </select>
</section>
<h4>My Div Section</h4>
<section>
  <button>change last selected div</button>
  <div class=editable></div>
  <div class=editable></div>
  <div class=editable></div>
</section>
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91