search
HomeWeb Front-endJS TutorialA brief discussion on Javascript event simulation_javascript skills

This means that the appropriate events will bubble up and the browser will execute the assigned event handlers. This ability is very useful when testing web applications. The DOM level 3 specification provides methods to simulate specific events. IE9 chrome FF Opera and Safari support this method. In IE8 and previous methods, IE browser has its own way to simulate events
a) Dom event simulation
You can create an event object at any time through the createEvent() method on the document. This method only accepts one parameter, which requires creating an event. The event string of the object. In the DOM2 level specification, all strings are in plural form. In DOM level 3 events, all strings are in singular form. All strings are as follows:
UIEvents: general UI events , Mouse events and keyboard events are all inherited from UI events, and UIEvent is used at DOM level 3.
MouseEvents: Universal mouse events, MouseEvent is used on DOM level 3.
MutationEvents: Universal mutation event, MutationEvent is used at DOM level 3.
HTMLEvents: Universal HTML events, there is no equivalent at DOM3 level.
Note that IE9 is the only browser that supports DOM3 level keyboard events, but other browsers also provide other available methods to simulate keyboard events.
Once an event object is created, the relevant information of the event must be initialized. Each type of event has a specific method to initialize. After the event object is created, the event is applied to the event through the dispatchEvent() method. On a specific dom node so that it supports this event. This dispatchEvent() event supports one parameter, which is the event object you created.
b) Mouse event simulation
Mouse events can be simulated by creating a mouse event object (mouse event object) and granting it some relevant information. Create a mouse event by passing a string to the createEvent() method" MouseEvents" to create a mouse event object, and then initialize the returned event object through the iniMouseEvent() method. The iniMouseEvent() method accepts 15 parameters. The parameters are as follows:
type string type: the type of event to be triggered, such as 'click' .
Bubbles Boolean type: Indicates whether the event should bubble. For mouse event simulation, this value should be set to true.
Cancelable bool type: Indicates whether the event can be canceled. For mouse event simulation, this value should be set to true.
View abstract view: The view granted by the event. This value is almost always document.defaultView.
Detail int type: Additional event information. This should generally default to 0 during initialization.
ScreenX int type: The X coordinate from the left side of the screen from the event
screenY int type: The y coordinate from the top of the screen from the event
clientX int type: The X coordinate from the left side of the visible area from the event
clientY int type : The y coordinate of the event distance above the visible area
ctrlKey Boolean type: Represents whether the ctrol key is pressed, the default is false.
 altKey Boolean type: represents whether the alt key is pressed, the default is false.
 shiftKey Boolean type: represents whether the shift key is pressed, the default is false.
MetaKey Boolean type: Represents whether the meta key is pressed. The default is false.
 Button int type: Represents the pressed mouse button, the default is zero.
 relatedTarget (object): The related object of the event. Only used when simulating mouseover and mouseout.

It is worth noting that the parameters of initMouseEvent() are directly mapped to the event object. The first four parameters are used by the browser. Only the event processing function uses other parameters. When the event object is passed as a parameter For the dispatch() method, the target attribute will be automatically assigned a value. The following is an example,

Copy code The code is as follows:

 var btn = document.getElementById( "myBtn");
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0,false , false, false, false, 0, null);
btn.dispatchEvent(event);

In DOM-implemented browsers, all other events, including dbclick, can be implemented in the same way.
c) Keyboard event simulation
It is worth noting that keyboard events have been moved out of DOM2-level events. Initially, in the draft version of DOM2-level events, keyboard events were included as part of the draft, but in the final version they were Moved out, FF has implemented the keyboard events in the draft version. It is worth noting that the keyboard events implemented in DOM3 level events are still very different from the keyboard events in the DOM2 level event draft version.
Creating a keyboard event object in a dom3 level event is through the createEvent() method and passing in the KeyBoardEvent string as a parameter. For the returned event object, call the initKeyBoadEvent() method to initialize it. The parameters for initializing the keyboard event are as follows: Each:
Type (string) - The type of event to be triggered, such as "keydown".
Bubbles (Boolean) — Represents whether the event should bubble.
Cancelable (Boolean) — Represents whether the event can be canceled .
 view (AbstractView) — The event is granted to the image. Usually the value is: document.defaultView.
 key (string) — The code corresponding to the pressed key.
 location (integer) — Pressed The position of the key. 0: Default keyboard, 1 left position, 2 right position, 3 numeric keyboard area, 4 virtual keyboard area, or 5 game controller.
 modifiers (string) — A space-separated modifier List.
Repeat (integer) — The number of times a key is pressed in a row.
Please note that in the DOM3 event, the keypress event is wasted, so in the following way, you can only simulate keydown and keyup events on the keyboard.
Copy code The code is as follows:

 var textbox = document.getElementById("myTextbox"), event;
if (document.implementation.hasFeature("KeyboardEvents", "3.0")){
event = document.createEvent("KeyboardEvent");
event.initKeyboardEvent("keydown", true, true, document.defaultView, "a",0, "Shift", 0);
  }
 textbox.dispatchEvent(event);

Under FF, you are allowed to create keyboard events by using document.createEvent('KeyEvents'). The initialization method is initKeyEvent(). This method accepts 10 parameters,
type (string) — The type of event to be triggered, such as "keydown".
bubbles (Boolean) — Represents whether the event should bubble.
Cancelable (Boolean) — Represents whether the event can be canceled.
 view (AbstractView) — The event is granted to the picture. The usual value is: document.defaultView.
 ctrlKey (Boolean) — represents whether the ctrol key is pressed. The default is false.
 altKey (Boolean) — represents whether the alt key is pressed. The default is false. .
 shiftKey (Boolean) — represents whether the shift key is pressed. Default is false.
 metaKey (Boolean) — represents whether the meta key is pressed. Default is false.
 keyCode (integer) — key is pressed or released. The key code corresponding to the key. The default is 0;
CharCode (integer) — The ASCII code corresponding to the character of the pressed key. The default used by the keypress event is 0.
D) Simulate other events
Mouse events and keyboard events are the most commonly simulated events in browsers, but sometimes mutation events and HTML events also need to be simulated. You can use createEvent('MutationEvents') to create a mutation event object. You can use initMutationEvent() to initialize this event object. The parameters include type, bubbles, cancelable, relatedNode, prevValue,
newValue, attrName, and attrChange. Yes Use the following method to simulate a mutation event:
var event = document.createEvent('MutationEvents');
event.initMutationEvent("DOMNodeInserted", true, false, someNode, "","","" ,0);
Target.dispatchEvent(event);
For HTML events, enter the code directly.
var event = document.createEvent("HTMLEvents");
event.initEvent("focus", true, false);
target.dispatchEvent(event);
For mutation events and HTML events are rarely used in browsers because they impose application restrictions.
E) Customized DOM events
In DOM3 level events, a type of event is defined called custom event. I call it customer event. Customer event will not be triggered by DOM natively, but will be provided directly. As for developers who can create their own events, you can create your own customer event by calling createEvent('CustomEvent'), calling the initCustomEvent() method on the returned event object, passing four parameters: type, bubbles, cancelable , detail. ps: My understanding of this part is limited, so I am just giving some advice here.
F) Event simulation in IE
From IE8, and earlier versions of IE, they imitate the way DOM simulates events: creating event objects, initializing event information, and then triggering events. Of course, IE's process of completing these steps is different.
First of all, different from the method of creating event objects in DOM, IE uses the document.createEventObject() method and has no parameters. It returns a general event object. Next, you need to assign a value to the returned event object. At this time, IE does not provide For the initialization function, you can only use physical methods to assign values ​​one by one, and finally call the fireEvent() method on the target element with two parameters: the name of the event handler and the created event object. When the fireEvent method is called, the srcElement and type attributes of the event object will be automatically assigned, and the others will need to be assigned manually. Please see the following example:
Copy code The code is as follows:

 var btn = document.getElementById ("myBtn");
 var event = document.createEventObject();
 event.screenX = 100;
 event.screenY = 0;
 event.clientX = 0;
 event. clientY = 0;
event.ctrlKey = false;
event.altKey = false;
event.shiftKey = false;
event.button = 0;
btn.fireEvent("onclick" , event);

This example creates an event object, and then initializes the event object with some information. Note that the assignment of event attributes is unordered. For event objects, these attribute values ​​are not very Important, because only the handler function corresponding to the event handler will use them. There is no difference between creating an event object for mouse events, keyboard events, or other events, because a generic event object can be triggered by any type of event.
It is worth noting that in Dom's keyboard event simulation, the result of a keypress simulation event will not appear as characters in the textbox, even if the corresponding event handler has been triggered.
Compared with DOM event simulation, I personally feel that IE's event simulation is easier to remember and accept. A unified event model can bring some convenience.
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool