Tuesday, June 10, 2008

Artificial Mouse Events in Javascript

I just learned one more how to create mouse events that are just like real user activities by using initMouseEvent.

For more detail, look at: http://developer.mozilla.org/en/docs/DOM:event.initMouseEvent
In this link, there is a syntax and example. You can create an event and trigger an event.


/**
* Creates a dummy event object
*/
function createEvent(type){
if(document.createEvent) {
e = document.createEvent('MouseEvents');
}else if (document.createEventObject){
var e = document.createEventObject();
}

if(mapObj.getDomObj() && mapObj.getDomObj().dispatchEvent && e && e.initMouseEvent) {
e.initMouseEvent(type,true,true,document.defaultView,1,0,0,0,0,false,false,false,false,0,null);
}
return e;
}

/**
* Fires a mouse event on a dom object
* @param {Object} domObj
* @param {Object} type
* @param {Object} e
*/
function fireEvent(domObj, type, e){
if(domObj.dispatchEvent){
domObj.dispatchEvent(e);
} else {
domObj.fireEvent("on" + type, e);
}
}

2 comments:

Anonymous said...

What is mapObj supposed to be? I tried this code and mapObj is undefined. I'm thinking maybe just 'document' but then the ".getDomObj()" function doesn't make sense....

If I take out those lines that initialise the mouse events nothing happens.

Anonymous said...
This comment has been removed by a blog administrator.

Subscribe in a Reader