16 ene 2013

Simulating mouse clicks in JavaScript




There might be times when you would like to simulate a mouse click on an DOM Node and don’t know how (for instance, submitting a form when in multi-frame environment).
Furthermore, it would be nice if the functionality could extend the DOM, so as to be able to use it combined with other pre-existing features.
Here’s the script bellow, just added and use it as you please (Ex. document.getElementById(”my_element”).click();)
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}

The code above is for Firefox only. For IE, just call document.getElementById(”my_element”).click() - it works by default, out of the box.
Quick code explanation:
  1. Extend/create the click function for the HTMLElement
  2. Create e new Mouse Event. The ownerDocument property returns the root element (document object) for a node. The createEvent arguments can be: “UIEvents”, “MouseEvents”, “MutationEvents”, and “HTMLEvents”.
  3. Ok, here you would normally have an initEvent, instead of initMouseEvent. The initEvent can take as parameters the name of the event, a boolean specifying whether or not the event can bubble (there are two phases, capture and bubble) and a boolean specifying whether or not the event’s default action can be prevented. The initMouseEvent can hold some other parameters (beside the ones from above), which you can check out here: initMouseEvent.
  4. Dispatches the event into the implementations event model.
For a nice guide of firing events (cross-browser wise), you can checkoutfiring javascript events properly, where there are some nice examples to think of.
Just to give a short receipt from Jehiah’s post:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}