Ok, I know that is a rookie question but is there any way to force a mouse click? To be more specific, say I want to trigger mouse click on random time and I don't know in which element the mouse would rest that time.
-
1Couldn't get exactly what you want. You should be more specific to get help. – axcdnt Apr 19 '12 at 12:05
-
4You cannot force a user mouse-click... – madflow Apr 19 '12 at 12:06
-
you can simulate a click event, but from your question it is not really clear what you want to do. Do you want to trigger a specific click on an element? do you want the click to be on the element the mouse is on atm? (that would be a bit complicated). – Rafael Herscovici Apr 19 '12 at 12:09
-
1There is no way to explain exactly what I want because that is just a part of really huge issue. @madflow answered my question, thanks :) – laxris Apr 19 '12 at 12:11
-
I would hate the page which is randomly clicking around... – Teemu Apr 19 '12 at 12:15
3 Answers
You can install a root level event handler on the document object to track the mouse position so you can know where the mouse is at any given time. You can create events in the browser using the code described in this post: Is it possible to trigger a link's (or any element's) click event through JavaScript? which gets its info from this article: http://jehiah.cz/a/firing-javascript-events-properly
Usually, creating raw events is not the most efficient way to solve a problem (unless you're doing some sort of automated tester). Usually it's better to just call the function you want directly or modify the DOM object directly rather than try to cause that change with an event.
-
Tracking mouse position isn't a very reliable method for finding out which element is hovered, as it'll have to cycle through all elements and their positions, offsets, dimensions, z-index, parent scroll offsets at every attempt to trigger a click, as these may change over time. – David Hedlund Apr 19 '12 at 12:34
-
@DavidHedlund - Every mouse event comes with `e.target` which tells you which element was originally targeted by the mouse event. That is already done for you. – jfriend00 Apr 19 '12 at 12:40
-
ah, of course, I was thrown off track with the *mouse position* remark, thinking that's what you'd derive your information from. – David Hedlund Apr 19 '12 at 12:52
No, this is not possible exactly the way you describe.
You can listen to mouseenter
for everything and always update a reference to whatever was hovered last.

- 128,221
- 31
- 203
- 222
-
-
If you listen to `mouseenter` you will get a reference to the hovered element. – David Hedlund Apr 19 '12 at 12:24
You can track elements with mouseover/mouseout and trigger their click handlers at any time

- 1,225
- 1
- 20
- 32
-
1unfortunately that is not the case..There is no way to know which element the mouse is over..thanks anyway :) – laxris Apr 19 '12 at 12:16