The events in JS

Source: Internet
Author: User

What do you need to know about events?

For events, first, we need to understand such concepts as events, event handlers, event types, event streams, event bubbling, event captures, event objects, event-related performance optimizations (event delegates, removal event handlers), and common browser compatibility issues.

The concept of events

Event: Refers to a specific interaction moment that occurs in a document or in a browser window. We can use listeners (or handlers) to schedule events so that the corresponding code executes when the event occurs.

Event handlers

Event handlers: The actions that our users click on the page, the movement of the mouse, the action of the page load, etc., can be called the event name, namely: click, MouseMove, load, etc. are the name of the event. A function that responds to an event is called an event handler, or an event listener.

Next we use a piece of code to illustrate the above two abstract concepts, specifically explained in code comments:

    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <div id= "Main" > Understanding the Basic concepts of events </div>
    6. </body>
    7. <script>
    8. var main = document.getElementById (' main ');
    9. Here click, Tap, is the name of an event, which is the instant that a click occurs in the browser window. On this word, in fact, is to let click this event corresponding, therefore, the onclick is called the event handler. In the following code, we use the handler (onclick) to book a click for the element main (click), which executes the code in the function (a dialog box pops up) when clicked.
    10. Main.onclick = function () {
    11. Alert (' Click here Oh! ‘);
    12. }
    13. </script>

About event handlers, from the initial development to the present, have undergone several changes.

The name of the event handler begins with "On", so the handler for the Click event is the onclick. At first, the HTML event handler is used, that is, an element (such as a DIV) that supports each event can be made using an HTML attribute with the same name as the corresponding event handler (that is, a property of the tag), and the value of this attribute is the JavaScript code that can be executed. For example:

    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <p onclick= "alert (' click ')" >html event handlers </p>
    6. </body>

Of course, we can also onclick= "" in the function of the call.

However, there are many problems with HTML event handlers that are exposed either way:

    1. First of all, the HTML code domain JavaScript code tightly coupled together, does not realize the separation, in the code update and maintenance of the time is very difficult.
    2. Second, the scope chain of an extended event handler can cause different results in different browsers.
    3. Third, if you do not call the function of the way, but as the example of the direct writing code, then the code is very poor, it will make the whole station code is very large, poor versatility. If extracted, stored in the function, then, there is another problem-when the function is not defined, just HTML, CSS code is loaded, the user clicks, will be completely unresponsive.

Based on these problems, people gradually improve the event handler, at this time, there is a DOM0 level event handler. (appears in the fourth generation Web browser)

What does the DOM0 level event handler look like? In fact, it is our usual most commonly used event binding, as in the following example:

    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <p id= ' btn ' >dom0 level event handlers </p>
    6. </body>
    7. <script>
    8. var btn = document.getElementById (' btn ');
    9. Btn.onclick = function () {
    10. alert (this.innerhtml);
    11. }
    12. </script>

After the DOM0-level event handler is launched, it is widely used by various users, but there is a problem that is not allowed when I want to bind more than one type of event to the same element/tag (for example, to bind 3 click events to the P tag above). Then, at this point, there is another event handler, the DOM2 level event handler, in the DOM2 level, defined two basic methods for handling the specified (that is, binding) and delete event handlers, respectively, AddEventListener () and RemoveEventListener (), ie9+, FireFox, Safari, Chrome, and opera all support DOM2-level event handlers. For ie8-, an IE proprietary event handler is used: two similar methods--attachevent () and DetachEvent ().

The specific example code is as follows: (taking AddEventListener as an example, two ways of writing are given)

    1. <!doctype html>
    2.      <meta charset= "UTF-8";
    3.     <title> Events-Solo Binghai </title>
    4. <body>
    5.     <p id= ' btn ' >dom0 level event handlers </p
    6. </body>
    7. <script>
    8.     var btn = document.getElementById (' btn ');
    9.     btn.addeventlistener ("Click", Test, false);
    10.     function Test () {
    11.         alert ( this.innerhtml);
    12.     }
    13. </script>
    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <p id= ' btn ' >dom0 level event handlers </p>
    6. </body>
    7. <script>
    8. var btn = document.getElementById (' btn ');
    9. Btn.addeventlistener ("click", Function () {
    10. alert (this.innerhtml);
    11. }, False);
    12. </script>

The third parameter in AddEventListener () and RemoveEventListener () represents the event stage at which the event is handled, and if false, refers to the bubbling phase, or, if true, the capture phase.

In the event, IE and FF have a series of compatibility issues, specific issues can be seen in the blog "IE browser and FF Firefox browser compatibility issues on the event"

On how to create an event listener that is compatible with all browsers, we'll do a detailed introduction and code demonstration in the next blog post, "cross-browser event handlers-handling DOM2-level event compatibility."

Event Type

Earlier in the course, we divided the events into three main categories, namely, general events, form events, and page events. Now we can do the subdivision again:

    1. UI events: such as load, unload, error, resize, scroll, select, Domactive, are triggered when the user interacts with elements on the page.
    2. Focus events: such as Blur, Domfocusin, Domfocusout, Focus, Focusin, focusout, triggered when an element gets or loses focus, the most important of these events is blur and focus, one that needs attention, This type of event does not bubble!
    3. Mouse and Wheel events: such as click, DblClick, MouseDown, MouseEnter, MouseLeave, MouseMove, Mouseout, MouseOver, MouseUp, is triggered when the user performs an action on the page with the mouse.
    4. Wheel event: MouseWheel (ie6+ supported), Dommousescroll (FF supported, same as MouseWheel effect). is triggered when the mouse wheel is used.
    5. Text event: textInput, enter text trigger in document.
    6. Keyboard events: KeyDown, KeyUp, KeyPress, triggered when the user performs an action on the page through the keyboard.
    7. Composition event: The DOM3 level is added to process the input sequence of the IME. The so-called IME, which refers to the Input Method Editor, allows the user to enter characters that are not found on the physical keyboard. Compositionstart, compositionupdate, compositionend three kinds of events.
    8. Change events: Domsubtreemodified, domnodeinserted, domnoderemoved, domattrmodified, domcharacterdatamodified, etc. Triggered when the underlying DOM structure has changed. Ie8-not supported.
    9. Change Name event: refers to triggering when an element or attribute name changes, and is currently deprecated!

For the basic types of events, with the advent and development of HTML5, but also added the HTML5 events, equipment events, touch events, gesture events and other events, we will introduce in detail later.

Event Flow

Event Flow: Describes the order in which events are received from the page.

IE with the original Netscape (Netscape), for the event stream is presented in a completely different order. The IE team proposes an event bubbling stream; The Netscape event stream is the event capture stream.

Event bubbling

Event bubbling: Indicates that the event starts with the most specific element (the node with the deepest nesting level in the document) and then propagates up to the less specific node (document).

Event capture

Event Capture: Indicates that the event is initially received by the least-specific node and then propagated down to the most specific node.

Consider an example:

    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <div id= "Main" >
    6. <p> Understanding the basic concepts of events </p>
    7. </div>
    8. </body>

If you click the P tag, the Click event is executed in the following order if it is the event flow mechanism of the event bubbling stream: p--div--body--html--document.

If the event flow mechanism of the capture stream is used, the Click event is executed in the following order: Document--html--body--div--p

For the event flow mechanism of a bubbling stream, the following compatibility issues exist:
    1. Document <=ie5.5, Div, body
    2. >=ie6.0, Div, body----HTML
    3. >=mozilla 1.0, Div------HTML, document----windows

You are welcome to learn from each other. Solo Binghai

Event Object

Event object: When an event on the DOM is triggered, an event object is generated, and in this object contains all the information related to the event. We write the following basic code:

    1. <!doctype html>
    2. <meta charset= "UTF-8" >
    3. <title> Events-Solo Binghai </title>
    4. <body>
    5. <div id= "Main" > Understanding the Basic concepts of events </div>
    6. </body>
    7. <script>
    8. var main = document.getElementById (' main ');
    9. Main.onclick = function (event) {
    10. Console.log (event);
    11. }
    12. </script>

Use Console.log to print out results such as.

There are two of them, which we use most often, namely type and target.

Type indicates the kind of event being triggered;

Target represents the destination of the event.

Other information, such as:

    1. Bubbles: Indicates whether the event bubbled
    2. Cancelable: Indicates whether the default behavior of an event can be canceled
    3. Currenttarget: Represents the element that the event handler is currently processing an event for
    4. Defaultprevented: Indicates whether the Preventdefault () is called
    5. Detail: Represents event-specific details
    6. Eventphase: The stage that invokes the event handler handler: 1 for the capture phase, 2 for the target, and 3 for the bubbling phase

There is some other information, which is not listed here.

Event-Side performance optimizations

Talking about how to optimize performance in event--the removal of event delegates and event handlers

In JavaScript code, the more events you add to the page, the worse the performance of the page will be. The main causes of this problem are:

    1. Each function is an object and consumes memory. The more objects in memory, the worse the performance will be.
    2. The number of DOM accesses caused by all event handlers must be specified beforehand, delaying the interaction readiness of the entire page.

In order to optimize the performance of the page, we will use two methods, the one mentioned above-the removal of event delegates and event handlers.

Event delegate

Many people ask me when to use the event delegate, in fact, in a nutshell, when a page event handler is more, we usually use it.

Event delegation takes advantage of event bubbling, specifying only one event handler to manage all events of a single type. For example: We have an OnClick event handler for the entire page, so we don't have to set up an event handler (onclick) for each clickable element in the page. Or, look at an example.

effect: Click on different elements to perform different actions. do not use event delegates:

  1. <!doctype html>
  2. <meta charset= "UTF-8" >
  3. <title> Events-Solo Binghai </title>
  4. <style>
  5. *{margin:0;padding:0;}
  6. . Control span{
  7. Float:left;
  8. width:50px;
  9. height:50px;
  10. line-height:50px;
  11. font-size:32px;
  12. Text-align:center;
  13. border:1px solid #f00;
  14. }
  15. </style>
  16. <body>
  17. <div class= ' control ' >
  18. <span id= ' left ' > </span>
  19. <span id= ' first ' >1</span>
  20. <span id= ' second ' >2</span>
  21. <span id= ' third ' >3</span>
  22. <span id= ' right ' > R </span>
  23. </div>
  24. </body>
  25. <script>
  26. var left = document.getElementById (' left ');
  27. var first = document.getElementById (' first ');
  28. var second = document.getElementById (' second ');
  29. var third = document.getElementById (' third ');
  30. var right = document.getElementById (' right ');
  31. Left.addeventlistener ("click", Function () {
  32. Alert (' Click on the left word, perform related actions ');
  33. }, False);
  34. First.addeventlistener ("click", Function () {
  35. Alert (' to perform the relevant action for the first ordinal ');
  36. }, False);
  37. Second.addeventlistener ("click", Function () {
  38. Alert (' To perform the related action for the second ordinal ');
  39. }, False);
  40. Third.addeventlistener ("click", Function () {
  41. Alert (' to perform the corresponding operation for the third ordinal ');
  42. }, False);
  43. Right.addeventlistener ("click", Function () {
  44. Alert (' Click on the right word, perform related actions ');
  45. }, False);
  46. </script>

It's not hard to see that we used 5 event listeners, one for each set.

Use event delegates:

  1. <!doctype html>
  2. <meta charset= "UTF-8" >
  3. <title> Events-Solo Binghai </title>
  4. <style>
  5. *{margin:0;padding:0;}
  6. . Control span{
  7. Float:left;
  8. width:50px;
  9. height:50px;
  10. line-height:50px;
  11. font-size:32px;
  12. Text-align:center;
  13. border:1px solid #f00;
  14. }
  15. </style>
  16. <body>
  17. <div class= ' control ' id= ' control ' >
  18. <span id= ' left ' > </span>
  19. <span id= ' first ' >1</span>
  20. <span id= ' second ' >2</span>
  21. <span id= ' third ' >3</span>
  22. <span id= ' right ' > R </span>
  23. </div>
  24. </body>
  25. <script>
  26. var control = document.getElementById (' control ');
  27. Control.addeventlistener ("click", Function (e) {
  28. Note that ie8-'s browser is not considered here, and if you want to write event handlers that are compatible with all browsers, see the next blog post
  29. var target = E.target;
  30. The switch statement is used here, or if it can be used to determine
  31. Switch (target.id) {
  32. Case ' left ': {
  33. Alert (' Click on the left word, perform related actions ');
  34. Break
  35. }
  36. Case "First": {
  37. Alert (' to perform the relevant action for the first ordinal ');
  38. Break
  39. }
  40. Case "Second": {
  41. Alert (' To perform the related action for the second ordinal ');
  42. Break
  43. }
  44. Case "Third": {
  45. Alert (' to perform the corresponding operation for the third ordinal ');
  46. Break
  47. }
  48. Case ' right ': {
  49. Alert (' Click on the right word, perform related actions ');
  50. Break
  51. }
  52. }
  53. }, False);
  54. </script>

Briefly summarize the so-called event delegates: to the parent or ancestor of an element, or even to a page-bound event, and then take advantage of the principle of event bubbling to detect through an event target object and then perform the related operation. The advantage is:

    1. The number of event handlers is greatly reduced, and there is less time to set up the event handlers on the page (DOM references are reduced-that is, we get the tags by ID, and we need fewer lookup operations and Dom references).
    2. Document (note: The above example is not tied to the document, but is bound to the parent Div, the most recommended is binding on the document) the object can be quickly accessed, and can be added to it at any point in the page life time event handlers, There is no need to wait for the domcontentloaded or Load event. In other words, as long as the clicked element is rendered in the page, it immediately has the corresponding function.
    3. The entire page takes up less memory space, which improves overall performance.
Removing event handlers

Whenever an event handler is assigned to an element, a connection is established between the running browser code and the JavaScript code that supports the page interaction. The number of connections also directly affects the speed of the page execution. Therefore, when there is an outdated "empty event handler" in memory, it can cause memory and performance problems for the Web application.

So when does an "empty event handler" appear?

    1. There are events in the document, with some DOM node operations (RemoveChild, ReplaceChild, and so on) that remove the element, but the DOM node's event is not removed.
    2. innerHTML to replace a part of the page, the original part of the page has an event, not removed.
    3. An event handler that is caused by the page unload is stuck in the in-memory.

Workaround:

    1. Reasonable use of the event entrusted;
    2. When performing related operations, remove the event first and then remove the DOM node;
    3. Remove all event handlers from the OnUnload event before the page is unloaded.

Turn from:

Http://blog.163.com/[email protected]/blog/static/18046981201311735325175/

The events in JS

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.