Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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);
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top