41

I need a code to find current position of cursor in a textbox/textarea. It should work with chrome and firefox. Following is the code which I am using:

<!DOCTYPE html>
<html>
  <head>
    <script>
      function textbox()
      {
        document.getElementById('Javascript_example').value = document.activeElement.id;
        var ctl = document.getElementById('Javascript_example');
        alert(ctl);

        var startPos = ctl.selectionStart;
        alert(startPos);
        var endPos = ctl.selectionEnd;
        alert(endPos);
      }
    </script>
  </head>
  <body>

    <input id="Javascript_example" name="one" type="text" value="Javascript_example" onclick="textbox()">

  </body>
</html>

Any suggestion?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Perseus
  • 1,546
  • 4
  • 30
  • 55

2 Answers2

67

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

function textbox()
{
        var ctl = document.getElementById('Javascript_example');
        var startPos = ctl.selectionStart;
        var endPos = ctl.selectionEnd;
        alert(startPos + ", " + endPos);
}
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Really, you are kidding me. I removed the document.getElementById('Javascript_example').value = document.activeElement.id; line from my code. And it works. Thank you anyway. You have shown me the right way :) – Perseus Apr 19 '13 at 13:51
6

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})
Evan Shortiss
  • 1,638
  • 1
  • 10
  • 15
  • No. I want to get the position. Let say, if I click on JavaScript and insertion point/carret is after Java , then it should return 4 – Perseus Apr 19 '13 at 13:29
  • 1
    Ah I completely misunderstood, I interpreted "cursor" as meaning the mouse cursor. See this maybe: http://stackoverflow.com/questions/5149683/how-to-get-selected-text-caret-position-of-an-input-that-doesnt-have-focus – Evan Shortiss Apr 19 '13 at 13:34
  • 1
    English, so many ways to interpret something as simple as cursor ;) – Evan Shortiss Jul 17 '15 at 18:30