41

Trying to fire off (trigger) a click event. Its easy to do in jQuery, but cannot figure out how to set the coordinates of the event and send them along.

Essentially, I need to trigger a click at a specific location (which is calculated prior to the trigger() call).

Any way to do this (in jQuery or otherwise)?

Thanks -

2 Answers 2

50

Set the pageX and pageY properties (which are normalized) on the event object and pass it to .trigger(), like this:

var e = new jQuery.Event("click");
e.pageX = 10;
e.pageY = 10;
$("#elem").trigger(e);
Sign up to request clarification or add additional context in comments.

8 Comments

your code appears to run without errors, but the desired result (positioning cursor inside a content editable div) is not occurring. Does this method send a native click() event as if I physically clicked that location? It doesn't appear so. Thanks -
well, here is my real issue (see link to other post). I thought triggering a click() event might solve it - but apparently not: stackoverflow.com/questions/2844649/…
Still voting up though - your answer certainly was valid.
No, firing your own click events generally doesn't trigger the ‘default action’ associated with a real click. If you want to set the input focus in an editable div to a particular point you'll have some unpleasant browser-specific range-hacking code to do.
Not working with <canvas>. I tried with your code at page: codepen.io/r0ysy0301/full/grjaOp.
|
-3

The ".trigger()" call accepts an "extraParameters" parameter that you could use to stuff the XY coords in I would think. Documentation

.trigger("click", [x, y]);

1 Comment

you can pass an anonymous function as the second parameter of the .trigger call. That function returns a position function with the desired top and left values. function () { this.position = function() { this.left = x; this.top = y; }; }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.