⬆️ ⬇️

Software generation of DOM 2 Events

image



Introduction




Hello, Habracheloveki.

')

In this article I want to tell the community about such a useful thing as DOM Events. Everyone who is somehow connected to Javascript knows that in this language, events and their processing are one of the most important and frequently used properties, but not many people know how to generate these events programmatically. Actually, the article is devoted to this: it tells what it is, why it is needed, and how to use it. There will be no talk about listeners, although this topic is rather dough related to the one under consideration.







What is it?





DOM Events allow event-oriented programming languages, such as JavaScript, JScript, ECMAScript, VBScript and Java, to register various event handlers / listeners to element nodes within the DOM tree (HTML, XHTML, XUL, SVG) .



This, for example, onClick, onBlur, onMouseOver, and so on. These events are triggered by a specific user action: pressing a key, clicking, moving the cursor beyond the element boundaries. Ie, with a physical impact on the "controls". We will learn to run such events programmatically, without the use of input devices and manipulation.



Why do you need it?





The application can be found very different: just for fun, development of bots for bbmmorpg , scripts for automation, cheating (script for “Klavogonok”: inserting the right letter into the input line and running the onKeyUp event), “webdvolannost”, I even met the thought of writing some kind of unit - test. In general, how much fantasy is enough.



What kind of intelligent manuals on this topic, the Internet could not be found, so I decided to reduce and perpetuate my finds in Habré.



However, it is worth remembering the following:



The “manual” launch (generation) of an event does not create a default action associated with this event. For example, programmatically generating a focus event on an element does not mean it will receive focus, a manually generated submit event will not force the form to send data (use the form’s submit method), the generated keystroke event does not mean that the symbol will appear in the input field, a programmatic click on the link does not activate the transition through it, etc. Such restrictions are necessary for security purposes and to prevent scenarios of simulating user work and interaction with the browser.



How to use it?





In general, the algorithm is one:

- get the object of the DOM node on which the event will be hung;

- create an object of the required event module;

- initialize the event object;

- assign an event to the desired DOM node;



To get started, look at the existing modules:

- Events - parent module. All modules inherit it, as will be discussed below.

- HTMLEvents - includes DOM element events.

- UIEvents - keyboard events.

- MouseEvents - mouse events.

- MutationEvents - DOM tree modification events.



DOM 2 Events Structure




There are five DOM 2 events modules. Their names reflect the essence of the event:



Events





Htmlevents





Uievents





MouseEvents





Mutationevents





Other events (such as 'dblClick') are not part of the specification, and browsers do not require their support. Browsers that support them either choose the appropriate module (for example, 'dblClick' is very well suited for the MouseEvents module) or create a new module. You need to know in which module the browser will determine such an event.



Example event implementation - onClick




Fake events are created using the document.createEvent method, which accepts the name of the corresponding event module that includes the required event. The next step is to prepare the event using the initEvent method (the method name is different for each module) and, finally, to trigger the event on the specified element using the dispatchEvent method. If you use a more specific type of event, rather than a generic one, you can provide additional information about the event during its preparation. Somewhat messy, but the example will clarify:



To create a 'click' event on an element whose ID is equal to 'element_id', you must:



var element = document.getElementById('element_id'); //     var o = document.createEvent('MouseEvents'); //   ,     o.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); //    element.dispatchEvent(o); //     




Since the list of parameters for the methods of initializing events and their descriptions is too large, in order to avoid cluttering up the topic, I give a link by clicking on which you can get acquainted with them in more detail. tyts Also, the following are the names of the methods for initiating an event, which are arranged as links to pages with descriptions of parameters.



Examples of event initialization for all modules:




HTMLEvents and generic Events

initEvent ('type', bubbles, cancelable)



Uievents

initUIEvent ('type', bubbles, cancelable, windowObject, detail)



MouseEvents

initMouseEvent ('type', bubbles, cancelable, windowObject, detail, screenX, screenY, clientX, clientY, ctrlKey, altKey, shiftKey, metaKey, button, relatedTarget)



Mutationevents

initMutationEvent ('type', bubbles, cancelable, relatedNode, prevValue, newValue, attrName, attrChange)



Note that although prevValue, NewValue, and attrName can be null, attrChange must always be defined, even if the event is not DOMAttrModified (value 1, 2, or 3)



MouseEvents is a subclass of UIEvents, in turn, the latter is a subclass of the Events module, so if you create a MouseEvents object, it will also inherit the initUIEvent and initEvent methods of UIEvents and Events interfaces. So you can choose the event initialization method you want to use when preparing it. (Nit * Event)



Event triggering using a generic event module (Inheritance Demonstration)




The example below demonstrates triggering an event that uses the universal initEvent method, and leaves properties in their default values ​​undefined (however, even if you use the common initEvent or initUIEvent, you must still use the exact module name, not the name of the generic module, or it will not work in Mozilla / Firefox, Konqueror, Safari):



 var element = document.getElementById('element_id'); var o = document.createEvent('MouseEvents'); o.initEvent('click', true, true); //     Events,     MouseEvents,     element.dispatchEvent(o); 




Keyboard events




Keyboard events are a bit more complicated, because Mozilla / Firefox does not implement the standard correctly, and will not allow you to create key events using generic UIEvents (it may just hang or “fall” with a critical error). Instead, it provides the internal module “KeyEvents, and the initialization method„ initKeyEvent “. The initKeyEvent method takes the following parameters: 'type', bubbles, cancelable, windowObject, ctrlKey, altKey, shiftKey, metaKey, keyCode, charCode. You can use the if construct (window.KeyEvent) to detect support for the KeyEvents module in the browser. Browsers that use UIEvents do not have a specific initialization function for key events, so some properties must be added manually:



 var element = document.getElementById('element_id'); if( window.KeyEvent ) //  FF { var o = document.createEvent('KeyEvents'); o.initKeyEvent( 'keyup', true, true, window, false, false, false, false, 13, 0 ); } else //    { var o = document.createEvent('UIEvents'); o.initUIEvent( 'keyup', true, true, window, 1 ); o.keyCode = 13; //   ,   initUIEvent    } element.dispatchEvent(evObj); 




Events in Internet Explorer




Initializing events in Internet Explorer is significantly different from other browsers. IE has a method for manually triggering an event called fireEvent, and is available with IE 5.5 +. In its simplest form, this is similar to the DOM version, but the bubbles and cancelable properties are not available. The fireEvent method is waiting for one or two parameters to be passed. The first must be the name of the event (for example, 'OnChange'), and the optional second parameter must be the event object passed to the handler.



Although the window object can detect multiple events in IE (for example, load, unload, scroll, resize — all of this should, according to the specification, be detected by the document object, not the window), this does not mean that fireEvent can be used with the window object .



 var element = document.getElementById('element_id'); if(document.createEvent) //    { var o = document.createEvent('MouseEvents'); o.initEvent('click', true, false ); element.dispatchEvent(o); } else if( document.createEventObject ) //  IE { o.fireEvent('click'); } 




If you want to specify additional information about the event, you must use the createEventObject method to replicate the CreateEvent and init * Event DOM methods. The createEventObject method usually returns an empty event object, and you will need to define the parameters yourself.



 var element = document.getElementById('element_id'); if(document.createEvent) //      { var o = document.createEvent('MouseEvents'); o.initMouseEvent( 'click', true, true, window, 1, 12, 345, 7, 220, false, false, true, false, 0, null ); element.dispatchEvent(evObj); } else if(document.createEventObject) //    IE { var o = document.createEventObject(); o.detail = 0; o.screenX = 12; o.screenY = 345; o.clientX = 7; o.clientY = 220; o.ctrlKey = false; o.altKey = false; o.shiftKey = true; o.metaKey = false; o.button = 0; o.relatedTarget = null; element.fireEvent('click', o); } 




Conclusion




I very briefly covered the topic, however, this is enough to understand its essence. The generation of events makes it possible to make many interesting things behind the screen, and given the number of available events, this topic becomes even more interesting.



The article provides only a few examples and types of events, however, it is quite easy to describe any of the others from the list at the beginning. Because of their large number, it will not be possible to tell about everything, but the names speak for themselves, so the inquisitive% username% will easily google the description of the desired event, the list of parameters it takes and the action it takes.



Successful to you life events without their random generation :)



What to read?




The article that served as the basis of this topic

Description of the structure of event modules: tables, comparisons.

About events on Mozilla MDN

Source: https://habr.com/ru/post/114244/



All Articles