Why does this code only work correctly once?

  • 0
    the idea is that when you press enter, there is a line break through
    and the pointer along with it
    but for some reason, at the second and so on, more than one press is added.
    <!DOCTYPE html>
    <html>
    <head>
    	<title></title>
    </head>
    <body>
     <div onkeyup="obr()" id="ds" contenteditable="true">
    var x = 0;</div>
     <script>
      function getCursorPosition(parent) {
      let selection = document.getSelection()
      let range = new Range
      range.setStart(parent, 0)
      range.setEnd(selection.anchorNode, selection.anchorOffset)
      return range.toString().length
    }
    
    function setCursorPosition(parent, position) {
      let child = parent.firstChild
      while(position > 0) {
        let length = child.textContent.length
        if(position > length) {
          position -= length
          child = child.nextSibling
        }
        else {
          if(child.nodeType == 3) return document.getSelection().collapse(child, position)
          child = child.firstChild
        }
      }
    }
      function obr(){
       var text = document.getElementById("ds")
       text = text.innerHTML
       text = text.replace(/var /gi,"<span style='color:red;'>var </span>")
       var icursor = getCursorPosition(document.getElementById("ds"))
       //console.log(icursor)
       document.getElementById("ds").innerHTML = text
       setCursorPosition(document.getElementById("ds"), icursor)
    
     //   var range = document.createRange();
    	// var myDiv = document.getElementById("ds");
    	// range.setStart(myDiv, 5);
    	// range.setEnd(myDiv, 5);
    	
     }
     document.addEventListener('keydown', function(event) {
    		
       if(event.key == "Enter"){
       		//console.log("d")
       		icursor = getCursorPosition(document.getElementById("ds"))
       		document.getElementById("ds").innerHTML += "<br> "
       		setCursorPosition(document.getElementById("ds"), icursor+=1)
       }})
    </script>
    </body>
    </html>
    JavaScript Anonymous, Jan 17, 2019

  • 0 Answers
Your Answer
To place the code, please use CodePen or similar tool. Thanks you!