Tuesday, August 14, 2007

Synthesizing Events in JavaScript

According to JavaScript: The Definitive Guide (4th ed), section 19.2.9 on Synthesizing Events, it says,

Unfortunately, at the time of this writing, the synthetic event API is not supported by Netscape 6, nor by the current version of Mozilla



But, it does work in the current version of Firefox (and IE). I had a situation where I needed to simulate events, so I wrote the following function to make it simple:


// simulateEvent
//
// simulate a user action
//
function simulateEvent(eventType, targetElement) {
var event;
targetElement = $(targetElement);

if (targetElement) {
// check for IE
if (window.ActiveXObject) {
event = document.createEventObject();
targetElement.fireEvent("on"+eventType,event);
} else {
switch (eventType) {
case "abort":
case "blur":
case "change":
case "error":
case "focus":
case "load":
case "reset":
case "resize":
case "scroll":
case "select":
case "submit":
case "unload":
event = document.createEvent("HTMLEvents");
event.initEvent(eventType, "true", "true");
break;
case "click":
case "mousedown":
case "mousemove":
case "mouseout":
case "mouseover":
case "mouseup":
event = document.createEvent("MouseEvents");
event.initMouseEvent(eventType, true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
break;
}
targetElement.dispatchEvent(event);
}
}
};

0 comments: