29

Is it possible to move the mouse so that it is positioned inside a text input using JavaScript?

2540625
  • 10,156
  • 8
  • 46
  • 53
Brian
  • 25,472
  • 52
  • 129
  • 168
  • 3
    You cannot move the actual mouse pointer in Javascript. – SLaks Feb 23 '10 at 23:36
  • 11
    You can, however move a pointer shaped image and pretend that you can. :-) – Andras Vass Feb 23 '10 at 23:38
  • 35
    Better yet, you can move a cat image around, following the mouse cursor, and try to use it to chase the cursor into the position you want. – jball Feb 23 '10 at 23:40
  • 4
    It's be a nightmare if mouse pointer or cursor can be moved. Havoc will break loose! – o.k.w Feb 23 '10 at 23:49
  • 10
    Just make the textbox big enough and never worry anymore. The mouse will always be inside of it. – Andras Vass Feb 24 '10 at 00:39
  • 1
    This browser experiment does seems to move cursor https://javier.xyz/control-user-cursor/ – B L Λ C K Oct 29 '17 at 15:18
  • Are you guys sure about that. What about dispatching your own mouse events? https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent – Azmisov May 16 '19 at 18:45

4 Answers4

29

I don't know about moving the actual rendered mouse pointer, but could you just set the focus on the element?

document.getElementById('the_text_input_id').focus()
BarryCap
  • 168
  • 1
  • 11
jasonbar
  • 12,945
  • 3
  • 36
  • 46
7

Please see this question:

Mouse move on element

Besides that, I think you are committing major design mistake by taking control of any of the users input in any way (maybe besides setting the focus of a form element)

JP Silvashy
  • 44,746
  • 48
  • 146
  • 219
7

Here is a function that select text in an input or textarea:

function textSelect(inp, s, e) {
    e = e || s;
    if (inp.createTextRange) {
        var r = inp.createTextRange();
        r.collapse(true);
        r.moveEnd('character', e);
        r.moveStart('character', s);
        r.select();
    } else if (inp.setSelectionRange) {
        inp.focus();
        inp.setSelectionRange(s, e);
    }
}

To place the cursor at the 12th position:

textSelect(document.getElementById('theInput'), 12);

To select a portion of the input field:

textSelect(document.getElementById('theInput'), 12, 15);
BarryCap
  • 168
  • 1
  • 11
Mic
  • 24,186
  • 9
  • 56
  • 69
4

It would be a huge [security?] issue if they allowed for something like this. Imagine: you have a setInterval(function(){moveMouseToTopLeftCorner and alert garbage}, 1)...
The user would have his mouse moved to the top left. And then alert would show up [which could be closed with enter].. upon which an alert would immediately pop up again.

You'd actually have to use your keyboard to open taskmanager and kill the browser >_>

However, it is probably possible with ActiveX [although thats IE only... and dumb]

Warty
  • 7,010
  • 1
  • 28
  • 47