event.simulate.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. var eventMatchers = {
  13. 'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
  14. 'MouseEvents': /^(?:click|dblclick|mouse(?:down|up|over|move|out))$/
  15. }
  16. var defaultOptions = {
  17. pointerX: 0,
  18. pointerY: 0,
  19. button: 0,
  20. ctrlKey: false,
  21. altKey: false,
  22. shiftKey: false,
  23. metaKey: false,
  24. bubbles: true,
  25. cancelable: true
  26. }
  27. Event.simulate = function(element, eventName) {
  28. var options = Object.extend(Object.clone(defaultOptions), arguments[2] || { });
  29. var oEvent, eventType = null;
  30. element = $(element);
  31. for (var name in eventMatchers) {
  32. if (eventMatchers[name].test(eventName)) { eventType = name; break; }
  33. }
  34. if (!eventType)
  35. throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
  36. if (document.createEvent) {
  37. oEvent = document.createEvent(eventType);
  38. if (eventType == 'HTMLEvents') {
  39. oEvent.initEvent(eventName, options.bubbles, options.cancelable);
  40. }
  41. else {
  42. oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
  43. options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
  44. options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
  45. }
  46. element.dispatchEvent(oEvent);
  47. }
  48. else {
  49. options.clientX = options.pointerX;
  50. options.clientY = options.pointerY;
  51. oEvent = Object.extend(document.createEventObject(), options);
  52. element.fireEvent('on' + eventName, oEvent);
  53. }
  54. return element;
  55. }
  56. Element.addMethods({ simulate: Event.simulate });
  57. })();