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();     
    savedSel = sel.saveCharacterRanges(el);
    cursorPos = sel.getRangeAt(0).toCharacterRange(el).start-1; 
  
    //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(cursorPos);
    $('#userInputlength').text(userInput.length);
    $('#userInput2length').text(userInput2.length);
    /* end debug */
    if(userInput2.length<userInput.length && cursorPos>userInput2.length )
    {
      /*
      alert("Spaces have been stripped and cursor position falls beyond Rangy's saved range--> Rangy won't be able to restore");
      */
      
      /*
      el.focus();
      rangy.getSelection().move("character", userInput2.length-1);
      */
     
    } else { //restore selection normally
    
    sel.restoreCharacterRanges(el, savedSel);
    
    }
}
Output

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

Dismiss x
public
Bin info
gibitopro
0viewers