views:

36

answers:

1

I'm now catching mouse click events on textarea elements.

Since I have to stop propagation after processing the event, the caret will not be set as usual when we use click on the textareas with middle key. But I need to set it before doing further works, so I tried to dispatch a mouse event manually.

My code is:

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 1, origEvt.screenX, origEvt.screenY,
    origEvt.clientX, origEvt.clientY, false, false, false, false, 0, null);
origEvt.target.dispatchEvent(evt);
...

This code tries to simulate a left click on the same element at the same position. The dispatched event can be caught, but however, the caret is not set.

Could anyone guide me how to do this?

+1  A: 

Faking events doesn't cause default actions to occur. You have to reproduce them yourself.

In this case you'd have to use selectionStart and selectionEnd to set the input focus position on the textarea. However getting the appropriate string offsets from a mouse location would be rather tricky.

It's not clear what the purpose is behind what you're trying to do, but you'll have to find another workaround. Maybe you could allow the default action to take place, but then blur the textarea after it has and focus it back later? You could also remember selectionStart​/​ selectionEnd properties just after the click to set focus back at any later point if the position might change in the meantime.

bobince
Thanks for the answer. But I cannot allow the default action to happen since under Gnome, middle-click will paste something at times.I'll have to find another way then...
ryanli
Horrible idea: allow the paste to take place but then revert the textarea to its previous value and set selection points to the place where the value was altered?
bobince
Yep, it's indeed horrible... Thanks. I've find another way round.
ryanli