0

I am trying to move a selection if collapsed outside of any commonAncestorContainer parentNode (the span that is created when using wrap button) and so far i've had no luck. Here is the code:

javascript

function wrapSelection(){
  var selection = window.getSelection();
  var span = document.createElement("span");
  span.style.fontWeight = "bold";
  
  if(selection.rangeCount){
    var range = selection.getRangeAt(0).cloneRange();
    
    if(!range.collapsed){
    range.surroundContents(span);
    }else{
      var newRange = document.createRange();
      newRange.setStartAfter(range.commonAncestorContainer.parentNode);
      selection.addRange(newRange);
    }
  } 
}

html

<html>
  <head>
  </head>
  <body>
    <input type="button" value="wrap" onclick="wrapSelection()" style="margin-bottom:10px;"/>
    <div id="my_textarea" style="height:50rem; width:50rem; border:1px solid #000;" contenteditable>
    </div>
  </body>
</html>

codepen: https://codepen.io/justinhdevelopment/pen/PoNaXzj

This will bring the selection inside the parentNode container if the selection is collapsed.. could someone please help me in bringing the selection after the parentNode container? The end result would be after wrapping text and clicking the wrap button a second time, the text inputted would not be wrapped since the selection is outside/after the span. Thank you so much in advance!

Justin Harris
  • 43
  • 1
  • 7

1 Answers1

0

Found the answer:

function placeCaretAfterNode(node){
  if(typeof window.getSelection != "undefined"){
    var range = document.createRange();
    range.setStartAfter(node);
    range.collapse(true);
    var selection = window.getSelection();
    selection.removeAllRanges();
    selection.addRange(range);
  }
}


function styleSelection(event){
  var selection = window.getSelection();
  var span = document.createElement("span");
  span.style.fontWeight = "bold";
  if(selection.rangeCount){
    var range = selection.getRangeAt(0).cloneRange();
    if(!range.collapsed){
      range.surroundContents(span);
    }else{
      placeCaretAfterNode(range.commonAncestorContainer.parentNode);
  }
} 
}

Set cursor after span element inside contenteditable div

Justin Harris
  • 43
  • 1
  • 7