157

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?

KatieK
  • 13,586
  • 17
  • 76
  • 90
Dennkster
  • 2,161
  • 2
  • 15
  • 13
  • 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 '11 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! – Jeremy Thompson Aug 16 '11 at 01: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 http://www.w3schools.com/jsref/met_win_scrollto.asp. – Stardust Dec 21 '15 at 19:25
  • 1
    Good luck with moving the mouse on smartphones. – Cœur Dec 18 '18 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. –  Oct 31 '19 at 00:35

10 Answers10

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
Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • 93
    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 02 '11 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. – Martin Jespersen Apr 12 '12 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 – Braden Best Dec 22 '12 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 '14 at 08:47
  • 1
    @jave.web: on the contrary, this would change everything. Consider how you would ever manage to use a site with ads on it - they'd all try to move your mouse to those ads - multiple ads would fight each other for cursor-control, and the user.. well there'd be no more surfing the web, what would be the point? – Martin Jespersen Nov 12 '14 at 23:11
  • @MartinJespersen ok it would change a bit - instead of a bunch of pop-ups, js-blocked-leaving the site and fake content to click a real content (etc...) there would be just straight forward way... – jave.web Nov 12 '14 at 23:40
  • @Martin Jesperson: Until Javascript simulates clicks the move movement simulation would not do any harm. The user can clearly see what he is clicking to and if he want to download file he sees dialogue box to confirm the download. I understand why Firefox does not has this feature. The purpose of JS is to control the web page not to control the users devices... That has sense. If this rule would be broken there would be something terribly wrong. But I still think the feature would be awesome! – John Boe May 22 '15 at 10:08
  • 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 '15 at 16:57
  • @dionyziz just press the nope button, haha – Lucas May 30 '17 at 13:29
  • but then how is it possible in the drag and drop API? – oldboy Nov 02 '17 at 23:10
  • If a hacker has control of your browser client then you've got bigger issues to worry about than cursor hijacking (they don't even need to move your cursor, they could issue `location='some_malicious_URI'`, etc.). – thdoan May 18 '18 at 04:54
  • you could do this in many ways without moving the position of the mouse... – BritishSam Aug 21 '19 at 12:51
  • Just start think on this for a second, if you could ;) It has moved cursor +2 pixels http://jsfiddle.net/onigetoc/rHJ5J –  Oct 31 '19 at 00:23
  • The answer assumes mousepointer must be moved by Javascript and assumes the OP owner think like that, but it is you thinkin like that and not PO. Move the cursor as PO told, not the mouse by Javascript - That is secure because it is possible to do ;) –  Oct 31 '19 at 01:15
  • @dionyziz exactly that, as if mouse moving / clicking was needed... – Mel Macaluso Jul 31 '20 at 12:44
  • I think a website can actually make keyboard keys do unexpected things, like changing default behavior for `Alt` + `F4`, or `Ctrl` + `W`, preventing the user from quitting the page, or clicking wrong link using `TAB`. Taking the fact that some users are not using any mouse controller, isn't this the same as taking over the cursor? (Sad that I couldn't put on the `` HTML for keys…) – BarryCap Jun 23 '21 at 20:40
  • I thought a website can customize a mouse pointer. How's that possible, could that be a solution? – france1 Sep 21 '22 at 16:54
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.

Alex Gray
  • 16,007
  • 9
  • 96
  • 118
  • 29
    I think we were all on board until "c executable"... xD – dGRAMOP Feb 11 '17 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 '17 at 01:36
  • 4
    C = 0 dependencies. Web is http. No cute homepage, here.. Just the transport. – Alex Gray May 24 '17 at 04:24
  • +1 for PS. Can we execute CGI calls using node dev-server or anything similar https://www.npmjs.com/package/http-server ?? – ATHER Apr 29 '18 at 03:47
  • 2
    Did anyone of you ever noticed the `Javascript` tag below the question? –  Oct 31 '19 at 01:21
  • I must say your method is ingenious – nonopolarity Mar 30 '21 at 05:55
  • @dGRAMOP there are Ruby or Python scripts that can do the same, so this is the captain saving you on the boat – nonopolarity Mar 30 '21 at 06:11
  • 2
    It is entirely possible: https://www.attejuvonen.fi/website-moves-your-cursor/ source code: https://github.com/baobabKoodaa/blog/blob/e91b6ab2843ca96ee3c93b48d248e683ffba0d6e/static/mouse/index.html –  Apr 01 '21 at 17:48
  • @user13372194 - No, he's just displaying an image of a cursor, ALMOST where your mouse is, and moving it around. Try moving the mouse outside the window border - it will suddenly jump in and out. – Sebastian Aug 04 '22 at 10:15
90

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

David Christiansen
  • 5,869
  • 2
  • 36
  • 42
Xaxis
  • 1,935
  • 15
  • 17
  • 6
    Yes, you can. You simply set the cursor style on a given element to 'none'. Give it a try. – Xaxis Jan 20 '11 at 21:19
  • 1
    ALSO, you could set the style of the cursor to a transparent 1x1 pixel image.. another simple solution. – Xaxis Jan 20 '11 at 21:24
  • 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 '11 at 07: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 02 '11 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 06 '13 at 19:19
  • @dionyziz you would be able to "keep moving" the image representing the mouse to the left even if the mouse leaves the webpage. Would advice to suspend any mouse event listeners while animating the image representation separately from the real mouse position and firing programmatically only those who come across the animation path. – Jaak Kütt Dec 05 '13 at 09:44
  • 5
    played around with this idea and made an example in JSFiddle http://jsfiddle.net/jaakkytt/9uczV/ – Jaak Kütt Dec 05 '13 at 13:35
  • @JaakKütt Trying to figure out where the pointer is actually moving, and clicking but couldn't figure it out. Example is too big with the flags taking up to much logic making it difficult to figure out. – mjs Oct 02 '16 at 21:42
  • @JaakKütt Is the only point where you actually control the pointer when the bomb is found? Then you can't click afterwards? Prior to that it's basically just replacing the original cursor img. Not actually moving or simulating it on a different location. – mjs Oct 02 '16 at 21:46
  • @momomo It is true that the example fiddle itself lacks a bit in documentation as it was a quickie to accompany the answer and discussion here. I put 5-10 flags there to allow the feeling of controlling the pointer sink in before it is lost upon finding the bomb. Replacing the original cursor image prior to the bomb is necessary so the pointer would match the image used for animation after finding the bomb. – Jaak Kütt Oct 06 '16 at 07:47
  • I am not sure about the question. If it is a pointer-lock we need so the background start moving then @dionyziz gave the nearest answer. To solve that problem we need to drag the view in same direction several times - not lifting the mouse from table. –  Oct 31 '19 at 00:05
  • I made a fully fleshed out "scary" april fools joke from this: https://www.attejuvonen.fi/mouse/ – Atte Juvonen Apr 13 '21 at 12:43
64

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!

dionyziz
  • 2,394
  • 1
  • 23
  • 29
  • 9
    Update: https://bugzilla.mozilla.org/show_bug.cgi?id=633602 and the w3 spec for pointer lock: https://dvcs.w3.org/hg/pointerlock/raw-file/default/index.html – chris Jan 30 '15 at 02: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 '15 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 02 '15 at 21:25
  • 7
    It's happened. And it's pretty awesome (if still vendor-prefixed): http://mdn.github.io/pointer-lock-demo/ – ericsoco Jun 22 '16 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](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API) – Tian van Heerden Mar 14 '17 at 11:39
  • 1
    @ericsoco The demo was moved into the [dom-examples repo](https://github.com/mdn/dom-examples/), so its github-pages URL was changed: https://mdn.github.io/dom-examples/pointer-lock/. (For the interested, links to all dom-examples demos: https://mdn.github.io/dom-examples/.) – Ken Bellows Jul 24 '17 at 12:03
  • That will cause big security problems. – Malus Jan Oct 02 '17 at 18:06
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'
    });        
});
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
Amish G
  • 519
  • 4
  • 2
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/

Codesmith
  • 5,779
  • 5
  • 38
  • 50
  • 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 '19 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

Dmitry Bosikov
  • 751
  • 6
  • 5
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.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Sanjay Verma
  • 1,390
  • 22
  • 40
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.

Sheavi
  • 250
  • 1
  • 7
  • 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 '13 at 06:50
  • but then how is it possible in the drag and drop API? – oldboy Nov 02 '17 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.

Eric Shoberg
  • 106
  • 1
  • 10
  • identical to Xaxis answer, essentially. – mathheadinclouds Oct 28 '19 at 00: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. – Eric Shoberg Nov 23 '19 at 19:05