158

I'm building a HTML5 game and I am trying to put the mouse cursor over a certain control on a specific event so that moving in a specific direction always has the same result. Is this possible?

5
  • If I understand correctly, you want to move the mouse cursor using JS - this isn't possible. You'll need to find another way.
    – thirtydot
    Jan 20, 2011 at 20:59
  • 1
    HTML5 has some new Mouse Events but nothing to move the mouse. You could always window.moveBy(x, y); to move the window underneath where the mouse hovers.. that'd be a pretty funky game:) The only othadox way I see it being done is via ActiveX - ewwww, yuk! Aug 16, 2011 at 1:54
  • 1
    No -- JavaScript won't let you do that, but I guess there could be a workaround that involves moving the page to a specific location, that would "move" the cursor as well, using the window scrollTo() -- see w3Schools at w3schools.com/jsref/met_win_scrollto.asp.
    – Stardust
    Dec 21, 2015 at 19:25
  • 1
    Good luck with moving the mouse on smartphones.
    – Cœur
    Dec 18, 2018 at 15:02
  • Image of a mousepointer can be moved around and set cursor:none. It is not a security risk because you are the programmer. If you can make a game you also can avoid the risk of clicking into your bank account while you are playing your game.
    – user985399
    Oct 31, 2019 at 0:35

10 Answers 10

242

You cannot move the mousepointer with javascript.

Just think about the implications for a second, if you could ;)

  1. User thinks: "hey I'd like to click this link"
  2. Javascript moves mousecursor to another link
  3. User clicks wrong link and inadvertently downloads malware that formats his c-drive and eats his candy
17
  • 95
    A webpage can force a download without requiring anyone to click a link, so what you claim isn't really a security issue. Being unable to move outside of the webpage window is, though.
    – dionyziz
    Feb 2, 2011 at 20:44
  • 12
    @dionyziz: There is quite a big difference between forced downloading into a sandbox and then userspace downloading started by user interaction. The security implications are actually very big. Apr 12, 2012 at 18:50
  • 8
    I think a dialogue box should ask a user if they want to allow mouse-trapping. If the user says 'no', none of that can happen Dec 22, 2012 at 19:05
  • 3
    @MartinJespersen tricking user interaction (not only clicking) was, is and will be always available, so this would not change a thing.
    – jave.web
    Oct 13, 2014 at 8:47
  • 7
    do you really need a mouse move event for that? couldn't the programmer just listen to a click event and change the url? Why make it noticeable? I'm not saying that I support someone doing this, just there is a smarter way to do it xD. Plus I'd imagine that the browser would only allow the mouse to click within the dom space and for only its domain.
    – jemiloii
    Sep 23, 2015 at 16:57
108
  1. Run a small web server on the client machine. Can be a small 100kb thing. A Python / Perl script, etc.
  2. Include a small, pre-compiled C executable that can move the mouse.
  3. Run it as a CGI-script via a simple http call, AJAX, whatever - with the coordinates you want to move the mouse to, eg:

    http://localhost:9876/cgi/mousemover?x=200&y=450

PS: For any problem, there are hundreds of excuses as to why, and how - it can't, and shouldn't - be done.. But in this infinite universe, it's really just a matter of determination - as to whether YOU will make it happen.

9
  • 30
    I think we were all on board until "c executable"... xD
    – dGRAMOP
    Feb 11, 2017 at 20:29
  • 1
    a web server? perhaps you mean a program with an http interface.. no need for web. The Go programming language might be advantageous over C in that it may make it easy to add the http part, or alternatively The nodejs interpreter would run code that could also include an http interface quite easily, as nodejs interpreter is built to make it easy to write server applications.
    – barlop
    May 24, 2017 at 1:36
  • 4
    C = 0 dependencies. Web is http. No cute homepage, here.. Just the transport.
    – Alex Gray
    May 24, 2017 at 4:24
  • 2
    Did anyone of you ever noticed the Javascript tag below the question?
    – user985399
    Oct 31, 2019 at 1:21
  • 2
    It is entirely possible: attejuvonen.fi/website-moves-your-cursor source code: github.com/baobabKoodaa/blog/blob/…
    – user13372194
    Apr 1, 2021 at 17:48
91

I would imagine you could accomplish placing the mouse cursor to a given area of the screen if you didn't use the real (system) mouse cursor.

For instance, you could create an image to act in place of your cursor, handle an event which upon detecting mouseenter into your scene, set the style on the system cursor to 'none' (sceneElement.style.cursor = 'none'), then would bring up a hidden image element acting as a cursor to be anywhere you like with in the scene based on a predefined axis/bounding box translation.

This way no matter how you moved the real cursor your translation method would keep your image cursor wherever you needed it.

edit: an example in jsFiddle using an image representation and forced mouse movement

12
  • 6
    Yes, you can. You simply set the cursor style on a given element to 'none'. Give it a try.
    – Xaxis
    Jan 20, 2011 at 21:19
  • 17
    This is the most thoughtful answer. And actually provides a real solution, while some other answers dot really add any value :) But how will webgl bring interesting games like FPS etc when we cant get any mouse lock, that sounds pretty limiting...
    – Dennkster
    Jan 23, 2011 at 7:51
  • 3
    That still has the problem of not being able to "keep moving" your mouse to the left. Once the mouse leaves the webpage, you can't keep controlling it.
    – dionyziz
    Feb 2, 2011 at 20:45
  • 2
    This is a perfect solution to this problem. The only reason there are people complaining is because it is not a trivial solution. You have to do some programming sometimes guys!
    – Marty
    Apr 6, 2013 at 19:19
  • 5
    played around with this idea and made an example in JSFiddle jsfiddle.net/jaakkytt/9uczV
    – Jaak Kütt
    Dec 5, 2013 at 13:35
65

Great question. This is really something missing from the Javascript browser API. I'm also working on a WebGL game with my team, and we need this feature. I opened an issue on Firefox's bugzilla so that we can start talking about the possibility of having an API to allow for mouse locking. This is going to be useful for all HTML5/WebGL game developers out there.

If you like, come over and leave a comment with your feedback, and upvote the issue:

https://bugzilla.mozilla.org/show_bug.cgi?id=630979

Thanks!

7
  • 9
    Update: bugzilla.mozilla.org/show_bug.cgi?id=633602 and the w3 spec for pointer lock: dvcs.w3.org/hg/pointerlock/raw-file/default/index.html
    – chris
    Jan 30, 2015 at 2:10
  • 55
    If this happens, I'll quit using a browser. :-P Seriously, websites just don't require the kind of consent you're giving when you install an application. This would be a great feature if we were all nice guys just employing this level of control to improve the user experience. Unfortunately the Internet is asshole-central, which is why there are a lot of really neat features we're hopefully never going to see in a browser. That being said: The fullscreen API would work to "lock out" the rest of the OS.
    – Mantriur
    May 29, 2015 at 22:47
  • 4
    @Someone Consent would be requested before such a lock is possible by an application (similar to how full screen consent is requested now in popular web browsers). Furthermore, the user can always revoke consent by hitting the ESC key.
    – dionyziz
    Nov 2, 2015 at 21:25
  • 7
    It's happened. And it's pretty awesome (if still vendor-prefixed): mdn.github.io/pointer-lock-demo
    – ericsoco
    Jun 22, 2016 at 23:30
  • 1
    @ericsoco Sadly that link is broken. This might help: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API Mar 14, 2017 at 11:39
51

You could detect position of the mouse pointer and then move the web page (with body position relative) so they hover over what you want them to click.

For an example you can paste this code on the current page in your browser console (and refresh afterwards)

var upvote_position = $('#answer-12878316').position();
$('body').mousemove(function (event) {
    $(this).css({
        position: 'relative',
        left: (event.pageX - upvote_position.left - 22) + 'px',
        top: (event.pageY - upvote_position.top - 35) + 'px'
    });        
});
5
  • 2
    Your post would be more valuable if you could post a code example that does it. Also, I suggest you to have a look to the FAQ : stackoverflow.com/faq
    – ForceMagic
    Oct 14, 2012 at 0:40
  • How do you actually click on the right element once the user clicks?
    – mjs
    Oct 2, 2016 at 21:41
  • @momomo You can use document.getElementByID('thingtoclick').click(); Dec 23, 2016 at 16:37
  • 2
    That was totally stellar! Way to think outside the box! I doubt it really provides what the questioner wanted, but as cool as it was, who really cares?
    – gcdev
    May 10, 2017 at 17:13
  • out of the box thinking :) numbers are off by the theme, but still great Aug 22, 2022 at 13:00
34

So, I know this is an old topic, but I'll first say it isn't possible. The closest thing currently is locking the mouse to a single position, and tracking change in its x and y. This concept has been adopted by - it looks like - Chrome and Firefox. It's managed by what's called Mouse Lock, and hitting escape will break it. From my brief read-up, I think the idea is that it locks the mouse to one location, and reports motion events similar to click-and-drag events.

Here's the release documentation:
FireFox: https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API
Chrome: http://www.chromium.org/developers/design-documents/mouse-lock

And here's a pretty neat demonstration: http://media.tojicode.com/q3bsp/

1
  • I'm taking this as the new accepted answer, because this is exactly the use-case I was asking for, even though it's not supported in all browsers.
    – Dennkster
    Nov 14, 2019 at 13:29
14

You can't move a mouse but can lock it. Note: that you must call requestPointerLock in click event.

Small Example:

var canvas = document.getElementById('mycanvas');
canvas.requestPointerLock = canvas.requestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
canvas.requestPointerLock();

Documentation and full code example:

https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API

8

Interesting. This isn't directly possible for the reasons called out earlier (spam clicks and malware injection), but consider this hack, which creates an impression of the same:

Step 1: Hide the cursor

Let's say you've a div, you can use this css property to hide the real cursor:

.your_div {
    cursor: none
}

Step 2: Introduce a pseudo cursor

Simply create an image, a cursor look-alike,mouse cursor imageand place it within your webpage, with position:absolute.

Step 3: Track actual mouse movement

This is easy. Check internet on how to get real mouse location (X & Y coordinates).

Step 4: Move the pseudo cursor

As the actual cursor move, move your pseudo cursor by same X & Y difference. Similarly, you can always generate a click event at any location on your webpage with javascript magic (just search the internet on how-to).

Now at this point, you can control the pesudo cursor the way you want, and your user will get the impression that the real cursor is moving.


Fair Warning: Do not do it. No one wants their cursor or computer controlled this way, unless if you've some specific use-case, or if you are determined to flee your users away.

4

You can't move the mouse pointer using javascript, and thus for obvious security reasons. The best way to achieve this effect would be to actually place the control under the mouse pointer.

2
  • 1
    The security implications are far from obvious. In fact, recent additions to standards introduce this ability without any serious security issues.
    – dionyziz
    Feb 27, 2013 at 6:50
  • but then how is it possible in the drag and drop API?
    – oldboy
    Nov 2, 2017 at 23:10
1

Couldn't this simply be done by getting actual position of the mouse pointer then calculating and compensating sprite/scene mouse actions based off this compensation?

For instance you need the mouse pointer to be bottom center, but it sits top left; hide the cursor, use a shifted cursor image. Shift the cursor movement and map mouse input to match re-positioned cursor sprite (or 'control') clicks When/if bounds are hit, recalculate. If/when the cursor actually hits the point you want it to be, remove compensation.

Disclaimer, not a game developer.

2
  • identical to Xaxis answer, essentially. Oct 28, 2019 at 0:25
  • @mathheadinclouds indeed, but is independent of browser implementation of the mouse-lock. So, essentially; but not. Thank you, for your opinion. - Edited: Never mind. I see what you're saying. I guess then, my only thought would be, this here is not un-useful. There is more layman to it, than the Xaxis answer. Nov 23, 2019 at 19:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.