5 common event parsing in the browser

Source: Internet
Author: User
Tags in degrees touch browser cache
This article brings you the content of the browser is commonly used in event resolution, there is a certain reference value, the need for a friend can refer to, I hope you have some help.

Form Events

Keyboard events

<input>triggered when <textarea> the value of a change occurs. Also, the input event is triggered when the value of the Contenteditable property is opened. One feature of the input event is that it triggers a continuous trigger, such as when the user presses the key one at a time, triggering an input event.

Such events include: KeyDown, KeyUp,

Mouse events

Select event is triggered when text is selected in <input>, <textarea>

The change event is triggered when the value of the <textarea> is changed when <input> <select> The most significant difference from the input event is that it does not trigger continuously, only when all modifications are complete, and the input event will inevitably cause a change event. Specifically, it is divided into the following situations:

    • Triggered when a radio box (radio) or check box (checkbox) is activated.

    • Triggered when the user commits. For example, complete the selection from the list below (select) and complete the selection in the date or file input box.

    • triggered when the value of a text box or TEXTAREA element has changed and loses focus.

    • The reset event is triggered by the form element when the form is reset (all form members are returned to the default value).

    • The submit event is triggered by the form element when the form data is submitted to the server.

Document events:


The Beforeunload event is triggered when the window is about to close, or the document and Web resource are about to unload. It can be used to prevent users from improperly closing Web pages. The default action for this event is to close the current window or document. If Event.preventdefault () is called in the listener function, or a non-null value is assigned to the ReturnValue property of the event object, a confirmation box is automatically popped out to let the user confirm that the page is closed. If the user clicks the "Cancel" button, the page will not be closed. The string returned by the listener function is displayed in the confirmation dialog box:

  Window.addeventlistener (' Beforeunload ', function (event) {    if (event.preventdefault) {      Event.preventdefault ();    } else {      Event.returnvalue = ' Are you sure you want to leave? ';    }  });

Unload and load

The Unload event is triggered when the window is closed or the Document object is about to unload, which occurs on objects such as window, body, frameset, and so on. Its triggering sequence is beforeunload, followed by the Pagehide event. The Unload event is only triggered when the page is not cached by the browser, in other words, if the page is unloaded by pressing forward/backward, the Unload event is not triggered. When the Unload event occurs, the document object is in a special state. All resources remain, but not visible to users, UI interactions (window.open, alert, confirm methods, etc.) are all invalid. The uninstallation of the document cannot be stopped even if an error is thrown.

The Load event is triggered when the page loads successfully, and the error event is triggered when the page load fails. Note that the page loads from the browser cache and does not trigger the Load event.

These two events actually belong to the progress event, not only to the document object, but also to the various external resources. Browsing the web is a process of loading various resources, images (image), stylesheets (style sheet), scripts (script), video (audio), Ajax requests (XMLHttpRequest), and so on. These resources and document objects, window objects, Xmlhttprequestupload objects, both trigger the Load event and the error event.

Pageshow and Pagehide

Pageshow event, Pagehide event: By default, the browser caches the page in the current session, and when the user taps the forward/Back button, the browser loads the page from the cache.
The Pageshow event is triggered when the page loads, including both the first load and the load from the cache. If you want to specify the code that runs every time the page loads (whether or not cached from the browser), you can put the listener function on the event. The first time it is loaded, its trigger order is queued behind the load event. The Load event does not fire when loading from the cache, because the Web page looks in the cache normally as it does after the Load event's listener function runs, so you do not have to repeat it. Similarly, if the page is loaded from the cache, the JavaScript script initialized within the Web page (such as the listener function for the domcontentloaded event) will not execute. The Pageshow event has a persisted property that returns a Boolean value. This property is false when the page is first loaded, and this property is true when the page is loaded from the cache.

Document.onpageshow = function (event) {} if  (event.persisted) {    //If storage cache is loaded  }}

Similarly, setting this property to True indicates that the page is to be stored in the cache, and set to false to indicate that the Web page is not saved in the cache, and if the listener function for the Unload event is set, the function will run immediately after the Pagehide event. If the page contains a frame, the Pageshow event and the Pagehide event of the frame page are triggered before the main page.

Domcontentloaded and ReadyStateChange

Domcontentloaded event when the HTML document is downloaded and parsed, the domcontentloaded event is triggered on the document object. At this point, only the parsing of the HTML document (the DOM generation of the entire page) is completed, and all external resources (style sheets, scripts, IFrame, and so on) may not have been downloaded at the end. In other words, this event occurs much earlier than the Load event. Note that the JavaScript script for the Web page is executed synchronously, so the listener function that defines the domcontentloaded event should be placed at the front of all scripts. Otherwise the script will delay triggering the domcontentloaded event once it has blocked. In addition, IE8 does not support domcontentloaded events and can be replaced with ReadyStateChange events.

The ReadyStateChange event occurs in the Document object and the XMLHttpRequest object, which is triggered when its ReadyState property has changed.

Other document-level events

The above highlights the domcontentloaded, ReadyStateChange, Pageshow, pagehide, unload, load, and Beforeunload events, in addition to the following events:

    • Onafterprint: script that runs after a document is printed

    • Onbeforeprint: script to run before document printing

    • onbeforeunload: script that runs before the document is unloaded (previously covered)

    • OnError: script that runs when an error occurs

    • Onhaschange: script that runs when a document has changed

    • OnLoad: Triggered after the page finishes loading (already covered above)

    • OnMessage: script that runs when a message is triggered

    • Onoffline: Scripts that run when a document is offline

    • Ononline: script to run when the document is online

    • Onpagehide: script to run when window is hidden (previously covered)

    • Onpageshow: script to run when window becomes visible (previously covered)

    • Onpopstate: script to run when window history changes

    • Onredo: script to run when document execution is undone (redo)

    • OnResize: Triggers when the browser window is resized

    • Onstorage: Scripts that run after the Web Storage zone update

    • OnUndo: script that runs when the document executes undo

    • Onscroll: Event executes script when document or document element scrolls

Mouse Events and MouseEvent objects

New MouseEvent (Typearg, mouseeventinit);

Built-in mouse events include:

    1. MouseDown: Press the mouse

    2. MouseUp: the mouse lifts up

    3. Click: Tap

    4. DblClick: Double-click

    5. MouseMove: Mouse Movement

    6. MouseOver: Mouse move in, bubbling

    7. Mouseout: Mouse move out, bubbling

    8. MouseEnter: Mouse move in, not bubbling

    9. MouseLeave: Mouse move out, not bubbling

    10. ContextMenu: Right-click menu

    11. Wheel: Roller Events

It has the following common properties:

    • The Altkey,ctrlkey,metakey,shiftkey property returns a Boolean value that indicates whether a key is pressed when a mouse event occurs;

    • The button returns the mouse key information for the event, with a value of 0 (left key), 1 or 4 (the middle key, 4 for the IE value), 2 (right-click), and a switch to select the execution point);

    • The Buttons property returns a 3 bit value that indicates which keys are pressed at the same time

    • Clientx,clienty returns the coordinates of the mouse position relative to the upper-left corner of the browser window, in pixels

    • Screenx,screeny returns the coordinates of the mouse position relative to the upper-left corner of the screen, in pixels

    • Movementx,movementy returns a displacement, in pixels, that represents the distance between the current position and the previous MouseMove event, on a numeric value:

Currentevent.movementx = Currentevent.screenx-previousevent.screenx
Currentevent.movementy = Currentevent.screeny-previousevent.screeny
    • The Relatedtarget property returns the secondary related node of the event, which is the node corresponding to the target property, such as: Mouseout target is the node that will be left, and relatedtarget refers to the node to be entered. This property returns null for events that do not have a secondary correlation node

    • The wheel event is an event related to the mouse wheel, and the browser provides a wheelevent constructor, new Wheelevent (Typearg, Mouseeventinit)

    • DeltaX: Returns a numeric value that represents the horizontal scroll volume of the Wheel

    • DeltaY: Returns a numeric value that represents the vertical scroll volume of the Wheel

    • Deltaz: Returns a numeric value that represents the z-axis scrolling amount of the wheel

    • Deltamode: Returns a numeric value that represents the unit of scrolling, applicable to the above three properties. 0 for pixels, 1 for rows, 2 for pages

Keyboard Event KeyboardEvent Object

Constructor new KeyboardEvent (Typearg, Keyboardeventinit)

Keyboard events include KeyDown (this event is triggered when the keyboard is pressed), KeyPress (as long as the key pressed is not CTRL, ALT, SHIFT, and meta, then the KeyPress event is triggered), KeyUp (triggering the event when the keyboard is released)

    • Altkey,ctrlkey,metakey,shiftkey: Returns a Boolean value that indicates whether the corresponding key is pressed

    • Key: Returns a String that represents the key name that was pressed. If you press the next control key and a symbol key at the same time, the key name of the symbol key is returned

    • KeyCode: Returns the ASCII code of the key, note: This is not case-sensitive, A键 whether output a or a keycode is 68. Using the Witch property in IE

Progress event Progressevent Object

New Progressevent (type, {  lengthcomputable:abooleanvalue,    //False as default  Loaded:anumber,                    //0 AS Default  total:anumber                      //0 as default});

Progress events are used to describe the process of an event's progress, such as the process of an HTTP request made by an XMLHttpRequest object,,,, the <audio> process of <video> <style> <link> loading external resources, including downloading and uploading. Typically, the following events are included:

    1. Abort event: Triggered when a progress event is aborted. If an error occurs that causes the process to abort, the event is not triggered.

    2. Error event: Triggered when an error causes a resource to fail to load, does not bubble. The listener function of the error event is best placed in an HTML attribute such as an IMG element.

    3. Load event: Triggered at the end of a successful progress.

    4. Loadstart event: Triggered at the start of a schedule.

    5. Loadend event: Triggered when progress is stopped, in the order that occurs after the Error event abort event Load event. The listener function of the Loadend event can be used to replace the listener function of the Abort event/load event/error event, and the Loadend event itself does not provide a reason for the end of the progress, but it can be used to do some of the actions that are required for all progress end scenarios.

    6. Progress event: When the operation is in progress, it is continuously triggered by the transmitted data block.

    7. Timeout event: Progress exceeded timed trigger

This type of event has the following properties:

    • Lengthcomputable: Returns a Boolean value that indicates whether the current progress has a computable length. If False, indicates that the current progress cannot be measured.

    • Total: Returns a numeric value that represents the overall length of the current progress. If you are downloading a resource over HTTP, it indicates the length of the content itself, without the length of the HTTP header. If the Lengthcomputable property is false, the total property cannot get the correct value.

    • Loaded: Returns a numeric value that represents the quantity that the current progress has completed. The attribute is divided by the total attribute, which gives you a percentage of the current progress.

Progress calculation if (e.lengthcomputable) {  var percentcomplete = e.loaded/e.total;}

Drag-and-drop event Dragevent Object

New Dragevent (type, drageventinit);

Drag-and-drop refers to the user holding down the mouse button on an object, dragging it to another location, and then releasing the mouse button to place the object there. There are several types of objects that are dragged, including Element nodes, images, links, selected text, and so on. In the HTML page, except the Element node can not be dragged by default, the other (pictures, links, selected text) can be dragged directly. To allow the Element node to be dragged, you can set the node's Draggable property to True. The Draggable property can be used with any element node, but the picture (img element) and the link (a element) are not added to this property, and are then dragged. For them, when used with this property, it is often set to false to prevent dragging. Note that once an Element node's Draggable property is set to True, it is no longer possible to select the text or child nodes inside the node with the mouse.

When the element node or selected text is dragged, the drag event continues to be triggered, including the following events:

    1. Drag event: During a drag-and-drop process, it is continuously triggered on the dragged node.

    2. DragStart event: Triggered on the dragged node at the start of the drag, the target property of the event is the dragged node. You should usually specify the dragged data in the listener function of this event.

    3. Dragend event: At the end of the drag (releasing the mouse button or pressing the Escape key) is triggered on the dragged node, the target property of the event is a dragged node. It is triggered on the same node as the DragStart event. The Dragend event is always triggered regardless of whether the drag is across the window or is canceled halfway.

    4. DragEnter event: Triggered on the current node when dragged into the current node, the target property of the event is the current node. You should typically specify whether or not to allow drop (drop) data to be dropped at the current node in the listener function of this event. If the current node does not have a listener function for the event, or if the listener function does nothing, it means that the data is not allowed to be dropped at the current node. The visual display of drag-and-drop into the current node is also set in the listener function of this event.

    5. DragOver event: A constant trigger on the current node when dragged over the current node, the target property of the event is the current node. This event is basically similar to the DragEnter event, which resets the effect of the current drag event (the DropEffect property of the DataTransfer object) to none, which means that the dragged node is not allowed to drop, so if the drop data is allowed on the current node, Typically, the Preventdefault method is used to cancel the reset drag effect to none.

    6. DragLeave event: Triggered on the current node when dragged away from the current node range, the target property of the event is the current node. Visually dragging away from the current node is set in the listener function for this event.

    7. Drop event: The dragged node or selected text, when released to the target node, is triggered on the target node. Note that if the current node does not allow drop, the event is not triggered even if the mouse button is released above the node. If the user presses the Escape key, the action is canceled and the event is not triggered. The listener function of the event is responsible for removing the dragged data and processing it.

There are a few things to note about drag-and-drop events:

    1. The drag-and-drop process only triggers these drag events, although the mouse is moving, but the mouse events do not trigger.

    2. Dragging files from the operating system into the browser does not trigger the DragStart and Dragend events.

    3. A listener function for the DragEnter and DragOver events that specifies the data that can be dropped (drop). Because most areas of the Web page do not work together as the target node for the drop, the default setting for these two events is that the current node does not allow drop. If you want to drop dragged data on the target node, you must first block the default behavior of both events, or cancel both events.

<p ondragover= "return false" >//or <p ondragover= "Event.preventdefault ()" >
    1. The drag event is represented by a Dragevent object that inherits the MouseEvent object, Dragevent object has only one unique property datatransfer, and the others are inherited properties. The DataTransfer property is used to read and write the data transmitted in the drag event, and all the drag events have a DataTransfer property that holds the data that needs to be passed, and the value of this property is a DataTransfer object. The dragged data holds two aspects of data: the type of data (aka format) and the value of the data. The type of data is a MIME string, such as Text/plain or image/jpg, and the value of the data is a string;

The value of the property of the DataTransfer object is an object that includes the following properties:

    • DropEffect Properties: Sets the effect of dropping (drop) when dragging a node, the possible values include copy (copy the dragged node), move (move the dragged node), link (create a link to the dragged node), none (Cannot drop the dragged node). Setting any of these values is not valid.

    • Effectallowed Properties: Set the allowable effects in this drag and drop, possible values include copy, move, link, copylink, Copymove, Linkmove, all, none, uninitialized (default, equivalent to all )。 If an effect is not allowed, the user cannot achieve this effect in the target node.

    • Files property: Is a FileList object that contains a set of local files that can be used to transfer in a drag operation. If this drag-and-drop does not involve a file, the property is an empty FileList object. Read the information about the dragged file through the Files property. If you want to read the contents of a file, use the FileReader object.

    • Types property: Is an array that holds each dragged data format, such as ' text/uri-list '

    • SetData () Method: Used to set the data of the specified type with the event. It takes two parameters, the first one is the data type, and the second is the specific data. If the specified type does not exist in the existing data, the type is written to the types property, and if it already exists, the existing data in that type is replaced.

Event.dataTransfer.setData ("Text/plain", "Text to drag");
    • The GetData () method takes a string (representing the data type) as a parameter, returning the data of the specified type with the event (usually the data added with the SetData method). If the data of the specified type does not exist, an empty string is returned.

Event.dataTransfer.getData (Types[0]);
    • The ClearData () method takes a string (representing the data type) as a parameter, deleting the data of the specified type with the event. If no type is specified, all data is deleted. If the specified type does not exist, the original data is not affected.

Event.dataTransfer.clearData ("Text/uri-list");
    • Setdragimage () can be used to customize the picture, it accepts three parameters, the first is an IMG picture element or a canvas element, if omitted or null, the appearance of the dragged node is used, and the second and third parameters are the horizontal and the right coordinates of the mouse relative to the upper-left corner of the picture.

Event.dataTransfer.setDragImage (IMG, 0, 0);

Touch events

New Touch (Touchinit);

Touch events include the following 5 types:

    1. Touchstart: Triggered when the user touches the touch screen, its target property returns the Element node where the touch occurred (using the Mspointerdown event in ie10+);

    2. Touchend: When the user is no longer touching the touchscreen (or when moving out of the edge of the screen), its target property is consistent with the target property of the Touchstart event, and its Changedtouches property returns a Touchlist object. Contains all touch points (touch objects) that are no longer touched (using the Mspointerup event in ie10+);

    3. Touchmove: Triggered when the user moves the touch point, its target property is consistent with the target property of the Touchstart event. The event is also triggered if the radius, angle, and force of the touch change. (Use Mspointermove event in ie10+);

    4. Touchenter: Triggered when the contact enters an element. There is no bubbling process for this event. (Use Mspointerover event in ie10+);

    5. Touchleave: Triggered when the contact leaves an element. There is no bubbling process for this event. (Use Mspointerout event in ie10+);

    6. Touchcancel: Triggered when the contact is interrupted for some reason. There are several possible reasons for the following (specific reasons vary depending on the device and browser):(there are no corresponding events in ie10+);

      1. Because an event cancels the touch: for example, the touch process is interrupted by a modal popup box or by a telephone;

      2. The contact leaves the document window and enters the browser's interface element, plugin, or other external content area;

      3. The number of contacts produced by the user exceeds the number of devices supported, causing the first touch object in Touchlist to be canceled.

The touch API consists of three objects. Each Touch object represents a touch point; Each contact is described by its position, size, shape, pressure size, and target element. The Touchlist object represents a list of multiple contacts. Specifically, the following properties are included:

  • Identifier property: Represents a unique identifier for a touch instance. It remains constant throughout the touch process (using the Pointerid attribute in ie10+);

  • Screenx/screeny property: Indicates the horizontal and vertical coordinates of the touch point relative to the upper-left corner of the screen, regardless of whether the page is scrolled or not;

  • Clientx/clienty property: Indicates the horizontal and vertical coordinates of the touch point relative to the upper-left corner of the browser viewport, regardless of whether the page is scrolled or not;

  • Pagex/pagey property: Indicates the horizontal and vertical coordinates of the touch point relative to the upper left corner of the current page, including the displacement caused by page scrolling;

  • Radiusx/radiusy property: Returns the x-axis and y-axis of the range of ellipses affected by the touch point, respectively, in pixels;

  • RotationAngle property: The rotation angle of the ellipse that represents the touch area, in degrees, between 0-90 degrees. The fingertip touches the screen and the touch range forms an ellipse, which is used to describe the ellipse area (using the rotation attribute in ie10+);

  • Force property: Returns a value between 0 and 1 that represents the touch pressure. 0 means no pressure, 1 represents the maximum pressure that the hardware can recognize (using the pressure attribute in ie10+, value 0-255);

  • Target property: Returns an element node that represents the node on which the touch occurred. When this contact is first tracked (in the Touchstart event), the contact is located in the HTML element. Even in the case of contact movement, the position of the contact has left the effective interactive area of the element, or the element has been removed from the document. It is important to note that if this element is removed during the touch process, the event will still point to it, but it will not bubble up the event to the window or Document object. Therefore, if there are elements that may be removed during the touch process, it is a best practice to bind the listener of the touch event to the element itself, preventing the element from being removed from being able to detect events bubbling from that element on its previous level element. Read-only property.

  • Altkey/ctrlkey/metakey/shiftkey are read-only properties: Returns a Boolean value that indicates whether a key is pressed at the same time as the touch

  • Changedtouches property: Returns a Touchlist object that contains all the touch objects (that is, related touch points) raised by the current touch event. It contains touch objects that represent all of the contacts from the last touch event to this event, where the state has changed. Read-only property.

  • Targettouches property: Returns a Touchlist object that contains all touch points that are still active within the target Element node of the touch.

  • The Touches property returns a Touchlist object (an object of an array of classes) that contains all the touch objects of the contacts that are currently touching the touch plane, regardless of which element they originated from, and whether or not their state has changed. Read-only properties

  • Type attribute: Refers to the types of this touch event.

  • Target property: The destination element for this touch event. This target element corresponds to the starting element of the contact in the touchevent.changedtouches (described in the following event type), but note that the starting element of the other contacts may be different in this event. In case you should use the target associated with each individual contact.

The following are the other properties in ie10+:

    • Hwtimestamp: Create Event time (MS);

    • Isprimary: Indicates whether the time is the main event;

    • PointerType: Takes value from event. Mspointer_type_touch, event. Mapointer_type_pen, event. Mspointer_type_mouse, means touch device;

    • Tilt[x| Y]: The degree of tilt of the pen;

To give a simple example:

function Handlemove (evt) {  evt.preventdefault ();//prevents the browser from continuing to handle touch events and also prevents mouse events from being emitted  var touches = evt.changedtouches; For  (var i = 0; i < touches.length; i++) {    var id = touches[i].identifier;    var touch = Touches.identifiedtouch (ID);    Console.log (Touch.pagex, Touch.pagey);}  }

For cross-platform interaction, I encapsulated a tap-related event as follows:

//The following code is not compatible with the lower version iefunction addtaplistener (node, callback) {var startevent = Window.onmousedown? Window.onmspointerdown?  ' Mspointerdow ': ' MouseDown ': ' Touchstart '; var event = Window.onclick?  ' Click ': ' Touch '; var endevent = window.onmouseup?  ' MouseUp ': ' Touchend ';    Node.addeventlistener (startevent, function (e) {var tap = document.createevent (' customevent ');    Tap.initcustomevent (' Tapstart ', true, true, null);  Node.dispatchevent (TAP);  });    Node.addeventlistener (event, function (e) {var tap = document.createevent (' customevent ');    Tap.initcustomevent (' Tap ', true, true, null);  Node.dispatchevent (TAP);  });    Node.addeventlistener (endevent, function (e) {var tap = document.createevent (' customevent ');    Tap.initcustomevent (' Tapend ', true, true, null);  Node.dispatchevent (TAP);  }); Node.addeventlistener (' tap ', callback);} 

Of course, this article only lists some common events, in fact, there are many events, this article will continue to update when necessary, but even so it is impossible to exhaust all the events, such as there are animation events: Animationstart, animation, Animationend and so on.

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.