17

Basically I'm trying to dispatch a custom made mouse click event to a text input element using the following code (see this jsFiddle):

function simulateClick(id) {
    var clickEvent = document.createEvent("MouseEvents");
    clickEvent.initMouseEvent("click", true, true, window, 1, 0, 0, 0, 0,
        false, false, false, false, 0, null);

    var element = document.getElementById(id);
    element.dispatchEvent(clickEvent);
}

When I run that code on a type="checkbox" element it works perfectly fine but it doesn't work at all when called on a type="text" element.

Now here's the definition of initMouseEvent() on MDN:

event.initMouseEvent(type, canBubble, cancelable, view, 
                 detail, screenX, screenY, clientX, clientY, 
                 ctrlKey, altKey, shiftKey, metaKey, 
                 button, relatedTarget);

So in the above example screenX, screenY, clientX and clientY would all be 0 (still, the above code works perfectly fine with checkboxes regardless of their position). I tried capturing a real event and passing the screen and client coordinates to the cusom made event, to no avail.

I though maybe text input elements ignore custom mouse events due to security reasons, but then element.focus() should't work either, which it does.

Any ideas or insights would be greatly appreciated!

Nux
  • 9,276
  • 5
  • 59
  • 72
Philip Kamenarsky
  • 2,757
  • 2
  • 24
  • 30
  • If i was you i'd consider using the jQuery library and then the `trigger`method - it works great cross browser, and will make your life a lot easier :) – Martin Jespersen Mar 18 '11 at 13:47
  • How are you determinating, the the click isn't working? When I add an `onclick` handler to your example it gets triggered: http://jsfiddle.net/epevj/11/ Are you expecting to get focus? Then why aren't you using `focus()`? – RoToRa Mar 18 '11 at 13:51

1 Answers1

5

As far as i can tell your code works fine. However it does not focus the input field as you may think, but the event is fired on the input field just fine, as seen in this fiddle: http://jsfiddle.net/ENvZY/

Note: the code is not crossbrowser compatible though, it fails in ie8.

Consider using a good crossbrowser library like jQuery instead of going the native DOM way - the wheel exists and works perfectly, reinventing it is a waste of time :)

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
  • The mouse click handlers are indeed called although the input field doesn't automatically acquire focus, as I incorrectly assumed and you pointed out :) I know about jQuery, this was just proof of concept code. Thanks! – Philip Kamenarsky Mar 18 '11 at 14:31