1+ /**
2+ * Event.simulate(@element, eventName[, options]) -> Element
3+ *
4+ * - @element: element to fire event on
5+ * - eventName: name of event to fire (only MouseEvents and HTMLEvents interfaces are supported)
6+ * - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
7+ *
8+ * $('foo').simulate('click'); // => fires "click" event on an element with id=foo
9+ *
10+ **/
11+ ( function ( ) {
12+
13+ var eventMatchers = {
14+ 'HTMLEvents' : / ^ (?: l o a d | u n l o a d | a b o r t | e r r o r | s e l e c t | c h a n g e | s u b m i t | r e s e t | f o c u s | b l u r | r e s i z e | s c r o l l ) $ / ,
15+ 'MouseEvents' : / ^ (?: c l i c k | d b l c l i c k | m o u s e (?: d o w n | u p | o v e r | m o v e | o u t ) ) $ /
16+ }
17+ var defaultOptions = {
18+ pointerX : 0 ,
19+ pointerY : 0 ,
20+ button : 0 ,
21+ ctrlKey : false ,
22+ altKey : false ,
23+ shiftKey : false ,
24+ metaKey : false ,
25+ bubbles : true ,
26+ cancelable : true
27+ }
28+
29+ Event . simulate = function ( element , eventName ) {
30+ var options = Object . extend ( Object . clone ( defaultOptions ) , arguments [ 2 ] || { } ) ;
31+ var oEvent , eventType = null ;
32+
33+ element = $ ( element ) ;
34+
35+ for ( var name in eventMatchers ) {
36+ if ( eventMatchers [ name ] . test ( eventName ) ) { eventType = name ; break ; }
37+ }
38+
39+ if ( ! eventType )
40+ throw new SyntaxError ( 'Only HTMLEvents and MouseEvents interfaces are supported' ) ;
41+
42+ if ( document . createEvent ) {
43+ oEvent = document . createEvent ( eventType ) ;
44+ if ( eventType == 'HTMLEvents' ) {
45+ oEvent . initEvent ( eventName , options . bubbles , options . cancelable ) ;
46+ }
47+ else {
48+ oEvent . initMouseEvent ( eventName , options . bubbles , options . cancelable , document . defaultView ,
49+ options . button , options . pointerX , options . pointerY , options . pointerX , options . pointerY ,
50+ options . ctrlKey , options . altKey , options . shiftKey , options . metaKey , options . button , element ) ;
51+ }
52+ element . dispatchEvent ( oEvent ) ;
53+ }
54+ else {
55+ options . clientX = options . pointerX ;
56+ options . clientY = options . pointerY ;
57+ oEvent = Object . extend ( document . createEventObject ( ) , options ) ;
58+ element . fireEvent ( 'on' + eventName , oEvent ) ;
59+ }
60+ return element ;
61+ }
62+
63+ Element . addMethods ( { simulate : Event . simulate } ) ;
64+ } ) ( ) ;
0 commit comments