Tuesday, 7 June 2011

Simulating native Javascript events

I just solved an issue that's been bugging me. When creating Javascript unit tests, I would like to trigger native DOM events. I'm using jQuery and despite what their API documentation says, some events not bound via jQuery cannot be triggered with the standard jQuery commands. So after some googling I've found a function that can be included in my unit tests to trigger those events:
window.simulateMouseEvent = function(eventName, element) {
	var evt = document.createEvent("MouseEvents");
	evt.initMouseEvent(eventName, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
	var cb = element
	var canceled = !cb.dispatchEvent(evt);
}
So a sample call could look something like this:
simulateMouseEvent("mouseup", $("#myControl")[0]);

No comments:

Post a Comment