simulate_event

Simulate mouse events

Tento skript by neměl být instalován přímo. Jedná se o knihovnu, kterou by měly jiné skripty využívat pomocí meta příkazu // @require https://update.greatest.deepsurf.us/scripts/21750/138530/simulate_event.js

  1. //// ==UserScript==
  2. // @name simulate_event
  3. // @namespace https://raw.githubusercontent.com/sergeych/jsnippets/master/simulate_event.js
  4. // ==/UserScript==
  5.  
  6. /**
  7. * $('#foo').simulate('click'[,options]); // => fires "click" event on an element with id=foo
  8. * Prototype's idea, modified to run under jQuery
  9. *
  10. * - options: optional object to fine-tune event properties - pointerX, pointerY, ctrlKey, etc.
  11. *
  12. **/
  13. (function(){
  14. var eventMatchers = {
  15. 'HTMLEvents': /^(?:load|unload|abort|error|select|change|submit|reset|focus|blur|resize|scroll)$/,
  16. 'MouseEvents': /^(?:click|mouse(?:down|up|over|move|out))$/
  17. };
  18.  
  19. var defaultOptions = {
  20. pointerX: 0,
  21. pointerY: 0,
  22. button: 0,
  23. ctrlKey: false,
  24. altKey: false,
  25. shiftKey: false,
  26. metaKey: false,
  27. bubbles: true,
  28. cancelable: true
  29. };
  30. jQuery.fn.simulate = function(eventName) {
  31. var element = this[0];
  32. var options = $.extend(true, defaultOptions, arguments[2] || { });
  33. var oEvent, eventType = null;
  34. for (var name in eventMatchers) {
  35. if (eventMatchers[name].test(eventName)) { eventType = name; break; }
  36. }
  37.  
  38. if (!eventType)
  39. throw new SyntaxError('Only HTMLEvents and MouseEvents interfaces are supported');
  40.  
  41. if (document.createEvent) {
  42. oEvent = document.createEvent(eventType);
  43. if (eventType == 'HTMLEvents') {
  44. oEvent.initEvent(eventName, options.bubbles, options.cancelable);
  45. }
  46. else {
  47. oEvent.initMouseEvent(eventName, options.bubbles, options.cancelable, document.defaultView,
  48. options.button, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
  49. options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, options.button, element);
  50. }
  51. element.dispatchEvent(oEvent);
  52. }
  53. else {
  54. options.clientX = options.pointerX;
  55. options.clientY = options.pointerY;
  56. oEvent = $.extend(document.createEventObject(), options);
  57. element.fireEvent('on' + eventName, oEvent);
  58. }
  59. return element;
  60. };
  61. })();