Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/dev/rangy-core.js"></script>
<script src="http://rangy.googlecode.com/svn/trunk/dev/rangy-textrange.js"></script>
  
  
  
<title>Rangy with replacement of innerHTML</title>
</head>
<body>
  
  
  <div id="area" contentEditable="true"; onkeyup="formatText();"></div>
  <br>
  <label>Cursor Position:</label>
  <span id="cursorPos"></span>
  <br><br>
  <label>UserInput Length:</label>
  <span id="userInputlength"></span>
<br><br>
    <label>UserInput2 Length:</label>
  <span id="userInput2length"></span>
  
</body>
</html>
 
#area {
    
    margin-left: 0px; 
    width:500px; 
    white-space: pre-wrap;      /* CSS3 */   
    white-space: -moz-pre-wrap; /* Firefox */    
    white-space: -pre-wrap;     /* Opera <7 */   
    white-space: -o-pre-wrap;   /* Opera 7 */    word-wrap: break-word;
    
    font: 62.5%"Trebuchet MS", sans-serif;
    min-height:2.4em;
    font-family: monospace;
    font-size: 2em;
    border: 2px solid #bbb;
    border-radius: 0.5em;
    padding: 0.2em 0.3em 0.2em 0.4em;
    background-color: white;
    outline: none; /* removes dotted outline */
    
    
}
 
var sel;
var savedSel;
var userInput;
var cursorPos;
function formatText() {
    el = document.getElementById("area");
    
    userInput = el.textContent || el.innerText; 
    sel = rangy.getSelection();
    var range = sel.getRangeAt(0);
  
    // Get the text preceding the selection boundaries and then remove whitespace to get the character offsets
    var rangePrecedingBoundary = range.cloneRange();
    rangePrecedingBoundary.setStart(el, 0);
    var selEndOffset = rangePrecedingBoundary.text().replace(/\s+/g, '').length;
    rangePrecedingBoundary.setEnd(range.startContainer, range.startOffset);
    var selStartOffset = rangePrecedingBoundary.text().replace(/\s+/g, '').length;
    rangePrecedingBoundary.detach();
    
  
    //strip spaces from userInput
    userInput2 = userInput.replace(/\s+/g, '');
    //apply style
    var newHTML = "<span style='color: green'>" +  userInput2 + "</span>";  
   
    //replace innerHTML of DIV
    el.innerHTML = newHTML;
    
    /* debug DIVs */
    $('#cursorPos').text(selStartOffset + " - " + selEndOffset);
    $('#userInputlength').text(userInput.length);
    $('#userInput2length').text(userInput2.length);
    /* end debug */
    range.selectCharacters(el, selStartOffset, selEndOffset);
    sel.setSingleRange(range);
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers