Active event dispatch in javascript _ javascript skills

Source: Internet
Author: User
Sometimes it is necessary to imitate some of the user's actions (mouse and keyboard operations), the most common is the mouse click. List 1, dispatchEvent ()
This is a standard method for triggering events. You must create an event object before using it. As follows:

The Code is as follows:


Var evt = document. createEvent ('event ');
Evt. initEvent ('click', true, true );
Element. dispatchEvent (evt );


2, fireEvent ()
This is the trigger event method implemented in earlier versions of IE. It does not need to create event objects and is directly used. As follows:

The Code is as follows:


Element. fireEvent ('onclick ');


Note: Like attachEvent, it needs to add "on"
A compatibility version of all browsers, as shown below

The Code is as follows:


Var dispatch = window. addEventListener?
Function (el, type ){
Try {
Var evt = document. createEvent ('event ');
Evt. initEvent (type, true, true );
El. dispatchEvent (evt );
} Catch (e) {alert (e )};
}:
Function (el, type ){
Try {
El. fireEvent ('on' + type );
} Catch (e) {alert (e )}
};


The above encapsulates a common method for triggering events, that is, various events can be triggered. The browser also provides specific methods to trigger separate events.
4, click ()
It is used to simulate user clicks. Except Safari/Chrome does not support non-input/button operations, it is supported by other browsers.
5, form. submit ()
Simulate form submission, relative to clicking input [type = submit]
6, input/textarea. select ()
Simulate the selected text.
7. focus ()
Obtains the cursor focus in a simulated manner.
8, blur ()
Simulate losing the cursor focus
9, input/textarea/select. change ()
Simulate text or option change
10. The distribution of custom events is actually to obtain the function and then call

Related:
Https://developer.mozilla.org/En/DOM/Element.dispatchEvent
Http://msdn.microsoft.com/en-us/library/ms536423%28v=VS.85%29.aspx
Https://developer.mozilla.org/en/DOM/Input.select

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.