Javascript event simulation _ javascript skills

Source: Internet
Author: User
Events are used to describe a specific interesting moment on a webpage. As we all know, events are usually triggered when the user interacts with the browser. Otherwise, Javascript can trigger specific events at any time, these events are the same as those created by the browser. This means that appropriate events will bubble up and the browser will execute the assigned event handler. This capability is very useful when testing web applications. It provides methods in the DOM Level 3 specification to simulate specific events, IE9 chrome FF Opera and Safari both support this method. IE8 and earlier ie browsers have their own methods to simulate events.
A) Dom Event Simulation
You can use the createEvent () method on the document to create an event object at any time. This method only accepts one parameter, that is, the event string of the event object to be created, in the DOM2 standard, all strings are in the plural form. In the DOM Level 3 event, all strings are in the singular form. All strings are as follows:
UIEvents: General UI events. mouse events Keyboard Events are inherited from UI events, and UIEvents are used at DOM Level 3.
MouseEvents: A common mouse event, which is used in DOM 3.
MutationEvents: A common MutationEvent. MutationEvent is used at level 3 of DOM.
HTMLEvents: Common HTML events, which are not equivalent to dom3.
Note that ie9 is the only browser that supports DOM3 Keyboard Events, but other browsers also provide other available methods to simulate Keyboard Events.
Once an event object is created, information about the event must be initialized. Each type of event has a specific method for initialization. After the event object is created, the dispatchEvent () to apply the event to a specific dom node so that it supports the event. This dispatchEvent () event supports a parameter, that is, the event object you created.
B) mouse event simulation
Mouse events can be simulated by creating a mouse event object, and some related information is granted to the mouse event. A mouse event is created by passing the createEvent () method to a string "MouseEvents ", to create a mouse event object, and then use the iniMouseEvent () method to initialize the returned event object. The iniMouseEvent () method accepts 15 parameters. The parameters are as follows:
Type string: the type of the event to be triggered, for example, 'click '.
Bubbles Boolean type: indicates whether the event should be bubbling. 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: view granted by the event. This value is almost all document. defaultView.
Detail int type: additional event information. The default value is 0 during initialization.
ScreenX int type: The X coordinate of the event to the left of the screen.
ScreenY int type: y coordinate of the event from the top of the screen
ClientX int: X coordinate of the event to the left of the visible area.
ClientY int type: y coordinate between the event and the visible area
CtrlKey Boolean type: indicates whether the ctrol key is pressed. The default value is false.
AltKey Boolean type: indicates whether the alt key is pressed. The default value is false.
ShiftKey Boolean type: indicates whether the shif key is pressed. The default value is false.
MetaKey Boolean type: indicates whether the meta key is pressed. The default value is false.
Button int type: indicates the mouse key pressed. The default value is zero.
RelatedTarget (object): the object associated with the event, which is only used to simulate mouseover and mouseout.

It is worth noting that the initMouseEvent () parameter maps directly to the event object. The first four parameters are used by the browser, and only the event processing function uses other parameters, when the event object is passed as a parameter to the dispatch () method, the target attribute is automatically assigned a value. The following is an example,

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, 0, null );
Btn. dispatchEvent (event );


In the browser implemented by DOM, all other events include dbclick, which can be implemented in the same way.
C) keyboard Event Simulation
It is worth noting that the keyboard event has been removed from the DOM2 level event. initially in the draft version of the DOM2 level event, the keyboard event was part of the draft, however, when the final version is removed, FF has implemented the keyboard event in the draft version, it is worth noting that there is still a big difference between the keyboard events implemented in DOM3 and the Keyboard Events in the DOM2 draft version.
To create a keyboard event object in a dom3 event, use the createEvent () method and input the KeyBoardEvent string as the parameter. Call the initKeyBoadEvent () method to initialize the returned event object, the following parameters are used to initialize a keyboard event:
Type (string)-type of the event to be triggered, for example, "keydown ".
Bubbles (Boolean)-indicates whether the event should be bubbling.
Cancelable (Boolean)-indicates whether the event can be canceled.
View (AbstractView)-The granted event is a graph. The usual value is: document. defaultView.
Key (string)-The code corresponding to the key to be pressed.
Location (integer)-the location where the key is pressed. 0: default keyboard, 1 left, 2 right, 3 digital keyboard, 4 virtual keyboard, or 5 game controllers.
Modifiers (string)-a list of modifiers separated by spaces.
Repeat (integer)-number of times a key is pressed in a row.
Note that the keypress event is charged in the DOM3 event. Therefore, you can only simulate the keydown and keyup events on the keyboard as follows.

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 );


In FF, you can use document. createEvent ('keyevents') to create a keyboard event. The initialization method is initKeyEvent (). This method accepts 10 parameters,
Type (string)-type of the event to be triggered, for example, "keydown ".
Bubbles (Boolean)-indicates whether the event should be bubbling.
Cancelable (Boolean)-indicates whether the event can be canceled.
View (AbstractView)-The granted event is a graph. The usual value is: document. defaultView.
CtrlKey (Boolean)-indicates whether the ctrol key is pressed. The default value is false.
AltKey (Boolean)-indicates whether the alt key is pressed. The default value is false.
ShiftKey (Boolean)-indicates whether the shift key is pressed. The default value is false.
MetaKey (Boolean)-Indicates whether to press the meta key. The default value is false.
KeyCode (integer)-the key code corresponding to the key when the key is pressed or released. The default value is 0;
CharCode (integer)-the ASCII code corresponding to the character of the key to be pressed. The default value for a total keypress event is 0.
D) simulate other events
Mouse events and Keyboard Events are the longest simulated events in the browser, but sometimes they also need to simulate sudden changes and HTML events. You can use createEvent ('mutationevents') to create a mutation event object. You can use initMutationEvent () to initialize this event object. parameters include type, bubbles, cancelable, relatedNode, prevValue,
NewValue, attrName, and attrChange. You can simulate a mutation event in the following way:
Var event = document. createEvent ('mutationevents ');
Event. initMutationEvent ("DOMNodeInserted", true, false, someNode, "", 0 );
Target. dispatchEvent (event );
For HTML events, directly add the code.
Var event = document. createEvent ("HTMLEvents ");
Event. initEvent ("focus", true, false );
Target. dispatchEvent (event );
Mutation events and HTML events are rarely used in browsers because they accept application restrictions.
E) custom DOM events
In DOM3 events, a class of events are defined as custom events, which are called Customer Events. Customer Events are provided directly instead of being triggered by dom, so that developers can create their own events, you can create a customer event of your own. By calling createEvent ('memevent'), you can call the returned event object and initCustomEvent () method. Four parameters are passed: type, bubbles, cancelable, detail. Ps: the younger brother has limited understanding of this part. Here, it is just a reference.
F) Event Simulation in IE
Both IE8 and earlier versions of IE are simulating DOM simulated events: Creating event objects, initializing event information, and then triggering events. Of course, the process for IE to complete these steps is different.
First, unlike the method used to create event objects in dom, IE uses document. createEventObject () method, without parameters, returns a common event object. Next, assign values to the returned event object. At this time, ie does not provide the initialization function, you can only assign values one by one using the physical method, and finally call the fireEvent () method on the target element. The parameters are two: the name of the event processing and the created event object. When the fireEvent method is called, The srcElement and type attributes of the event object are automatically assigned values, and other values are manually assigned values. See the following example:

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 );


In this example, an event object is created, and the event object is initialized through some information. Note that the assignment of event attributes is unordered and these attribute values are not very important for the event object, because only the event handler corresponding to the event handle will use them. There is no difference between the event objects that create mouse events, keyboard events, or other events, because a common event object can be triggered by any type of events.
It is worth noting that in Dom keyboard event simulation, the result of a keypress simulation event will not appear as a character in the textbox, even if the corresponding event processing function has been triggered.
Compared with DOM event simulation, I personally think that IE event simulation is easier to remember and accept, and a unified event model can bring some convenience.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.