A brief talk on JavaScript events (event simulation)

Source: Internet
Author: User

Events are often triggered by actions or by browser functions, and the elements can also be triggered by JavaScript. Events are triggered by JavaScript, also known as simulations of events.

    • Event simulation in DOM

The event object can be created by the CreateEvent method of the document. This method takes a parameter, which is a string representing the type of event to be created. At the DOM2 level, all of these strings are in the English plural and become singular in the DOM3 level. These strings are as follows: Uievents, generalized UI events, mouse events and keyboard events are inherited from the event, in the DOM3 level is uievent;mouseevents, generalized mouse events, in the DOM3 level is MouseEvent Mutationevents,dom Change event DOM3 level is mutationevent;htmlevents,html event, there is no corresponding DOM3 level.

After you create an event object, you also need to initialize it with information about the event. Each type of event has a corresponding method in which the event object can be initialized by passing in a parameter. The final step in the simulation event is to trigger the event, which uses the Dispatchevent method, which is supported by all nodes that support DOM events. Calling the Dispatchevent method requires passing in a parameter that represents the event object that is to be fired.

You can simulate mouse events by creating a mouse event object and specifying the necessary information for it. The object method that creates the mouse event is the CreateEvent method, and the passed in parameter is mouseevents. The returned event object has a Initmouseevent method that specifies information about the mouse event. This method receives 15 parameters, respectively, corresponding to the typical attribute one by one in the mouse event, with the following properties: Type, which represents the type of event to be triggered, such as "click"; bubbles, whether bubbling is supported, such as true;cancelable, indicates whether the event can be canceled, such as true , view, event-related views, Typically Document.defaultview;detail, event-related details, usually set to 0;screenx, event relative to the x-coordinate of the screen, ScreenY, event relative to the y-coordinate of the screen, ClientX, the x-coordinate of the event relative to the viewport, ClientY, event-relative The y-coordinate of the viewport, Ctrlkey, indicates whether the CTRL key is pressed, usually false;shiftkey, indicates whether the shit key is pressed, generally false;metakey, whether the meta-key is pressed, generally false;button, Indicates which mouse button is pressed, which defaults to 0;relatedtarget, which represents the object associated with the event, which is used when simulating mouseout and mouseover.

For mouse events to be simulated, it is generally only necessary to pass the first 3 parameters.

  

1 varcallback =function(event) {2Console.log ("1");3             }4Eventutil.addevent (document.getElementById ("Btnadd"), "click", callback);5             varEVT = Document.createevent ("mouseevents");6Evt.initmouseevent ("click",false,false);7             varBTN =document.getelementbyid ("Btnadd");8Btn.dispatchevent (EVT);

With the above event, we can trigger the Click event of the Btnadd element. First we bind the click event to the element, which requires a user action to be triggered. Line 5th creates the mouse event object through CreateEvent and initializes the event object through Initmouseevent. The event is then triggered by the Dispatchevent method of the element.

There is no specification for keyboard events in the DOM2 class. There is a clear definition of keyboard events in the DOM3 level. Calls the CreateEvent method, passing in KeyboardEvent to create keyboard events. The returned event object contains a Initkeyevent method. The parameters of this method are as follows: Type, event type, such as keydown;bubbles, whether the event supports bubbling, such as true;cancelable, whether the event can be canceled, such as True;view, the view of the event, Generally document.defaultview;key, which is the key code to press the key, the location, which indicates where the key is pressed, 0 means the default main keyboard, 1 for the left, 2 for the right, 3 for the numeric keypad, 4 for the mobile device, 5 for the handle; modifiers, a space-delimited list of modifier keys, such as S Hift;repeat, press this key number of times.

1 var txt=document.getelementbyid ("Inputtext"); 2             Txt.focus (); 3             var evt =document.createevent ("KeyboardEvent"); 4             Evt.initkeyboardevent ("KeyDown",false,false, Document.defaultview, "a", 0, "Shift", 0); 5             Txt.dispatchevent (EVT);

The above code simulates the KeyDown event while holding down the SHIFT key and the A key.

You can simulate mouse events, keyboard events, HTML events, and change events through JavaScript code. You can also simulate custom events.

  

1 varAdd=document.getelementbyid ("Btnadd");2Eventutil.addevent (Add, "MyEvent",function(EV) {3ev=eventutil.getevent (EV);4                 vartarget=eventutil.gettarget (EV);5Console.log (Ev.type);//MyEvent6             });7             varEvt=document.createevent ("Customevent");8Evt.initcustomevent ("MyEvent",false,false, "Hello");9Add.dispatchevent (EVT);

The above code creates the Customevent event object through the CreateEvent method, which is the custom event object, which initializes the object by Initcustomevent and finally triggers the MyEvent event. The 5th row of output events is of type MyEvent, which is our custom event.

The above method of creating a simulated event is not supported in IE8 and IE8 browsers below. You can use the following code to simulate an event.

1 var btn =document.getelementbyid ("Btnadd"); 2             Eventutil.addevent (BTN, "click",function(e) {3                 console.log ("click"); 4             })5             var evt=document.createeventobject (); 6             Btn.fireevent ("onclick", evt);

Finally, a scenario that is often used in event simulations, such as downloading a picture or exporting Excel, can be done through event simulations.

1 functiondownloadimg () {2                 varuseragent = navigator.useragent;//get the useragent string for the browser3                     varimg = document.createelement ("img");4Img.src= "Font-awesome-3.2.1/src/assets/img/fort_awesome.jpg";5Img.style.display= "None";6 Document.body.appendChild (IMG);7                  if(Useragent.indexof ("MSIE") > 1) {8                       varOPop = window.open (Img.src, "", "width=1, Height=1, top=5000, left=5000");9                      for(; OPop.document.readyState! = "complete"; )Ten                     { One                         if(OPop.document.readyState = = "complete") Break; A                     } -OPop.document.execCommand ("SaveAs"); - opop.close (); the                      -                 } -                  Else{ -                   +                     varEvt=document.createevent ("Mouseevents"); -Evt.initmouseevent ("click",false,false); +                     varA=document.createelement ("a"); AA.download= "Test.jpg"; ata.href=img.src; - a.dispatchevent (evt); -                  } -             } -Downloadimg ();

A brief talk on JavaScript events (event simulation)

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.