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);
}
}
};

2 comments:

BitShifter said...

YESSS!! This was exactly the example I was looking for; now we can do automated testing of all our AJAX pieces within our webapps. Thank you so much =>

Here's what I implemented (I only bothered coding for Mozilla as it's the only thing we can easily run our scripts from Greasemonkey with):

//A BIG SHOUT OUT TO Steven Pothoven - http://blog.pothoven.net/2007/08/synthesizing-events-in-javascript.html
var event = document.createEvent("HTMLEvents");
event.initEvent("keyup", "true", "true");
event.keyCode = 13;
document.getElementById('P201_ASSESSOR_SEARCH').dispatchEvent(event);
document.location.href = "javascript:doSubmit('SAVE')";

Lucas said...

Sweet, thank you. Needed something to simulate an venet in a Prado based application that I have been tasked to edit. This solved my issue.