title: How to get the caret's position in contentEditable div when entering a new line?
body: <p>I am making a rich text editor with UIWebview, which uses a <code>contentEditable</code> div. I want to get the caret's position in pixels. I have searched a lot, and I got the code below.</p>
  
  <pre><code>function getCaretClientPosition() {
    var x = 0, y = 0;
    var sel = window.getSelection();
    if (sel.rangeCount) {
      var range = sel.getRangeAt(0);
      if (range.getClientRects) {
        var rects = range.getClientRects();
        if (rects.length &gt; 0) {
          x = rects[0].left;
          y = rects[0].top;
        }
      }
    }
    return { x: x, y: y };
  }
  </code></pre>
  
  <p>The code above works well until I enter a newline. <code>sel.getRangeAt(0)</code> returns null, so the function can't return the right caret Y pixels.</p>