Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dispatchEvent() a mouse click to a <input type=text> element?

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!

like image 671
Philip Kamenarsky Avatar asked Mar 18 '11 13:03

Philip Kamenarsky


People also ask

What does dispatchEvent do in JavaScript?

The dispatchEvent() method of the EventTarget sends an Event to the object, (synchronously) invoking the affected EventListener s in the appropriate order. The normal event processing rules (including the capturing and optional bubbling phase) also apply to events dispatched manually with dispatchEvent() .

How do you click an element in JavaScript?

The element to be clicked first selected and the click() method is used. This simulates a click on the element. Example: The setInterval() function is used to call the function which simulates the click.

What are Dispatch events?

To dispatch an event means to "fire" it. The handlers listening to that event will be called.


1 Answers

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 :)

like image 155
Martin Jespersen Avatar answered Oct 12 '22 11:10

Martin Jespersen