views:

271

answers:

2

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 -

+3  A: 

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);
Nick Craver
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 -
OneNerd
@OneNerd - It does not, it's not possible to simulate events exactly like they happens, at least cross-browser. What are you doing with the result, is it a handler or an image map?
Nick Craver
well, here is my real issue (see link to other post). I thought triggering a click() event might solve it - but apparently not: http://stackoverflow.com/questions/2844649/javascript-contenteditable-getting-setting-caret-position
OneNerd
Still voting up though - your answer certainly was valid.
OneNerd
@OneNerd - Ah I see what you're after, I'm not sure there is a way to do what you're after *exactly*, correct me if I'm wrong, you want to replace the div with a textarea basically, with the cursor at the right position when it appears? e.g. the same as the text that was in the div? If you know or could calculate the coordinates (fixed width font I'd think and divide it out), you'd could use [an approach like this](http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area).
Nick Craver
Yeah its close -- big difference is I am using 2 DIVs (which can have nodes) as opposed to a textarea. You would think it would be easy to determine where mouse-click occurred on one div, and set that same coordinate on another -- but is appearing to be too tricky and/or impossible. I will tinker some more with the code in that post and see what I can come up with. Thanks -
OneNerd
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.
bobince
A: 

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]);
BradBrening