Explore five types of event handlers in JavaScript

Source: Internet
Author: User
Tags event listener script tag

We know that the interaction between JavaScript and HTML is implemented through events.  events were first seen in IE3 and Netscape Navigator 2, as a means of sharing server computing load. It is generally understood that an event is an action performed by the user or the browser itself. An event handler is a function that responds to an event. Extract the trunk, which is the event handler, as a function. We also refer to event handlers as event listeners. the event handler starts with "on", so the time handler for the event on is the onclick. There are roughly five time handlers in JavaScript, which are described in 5 parts according to these five different time handlers.

    1. HTML Event handlers
    2. DOM0 Level Event handlers
    3. DOM2 Level Event handlers
    4. IE Event handlers
    5. Cross-browser event handlers
First part: HTML event handlers

What makes an HTML event handler? Obviously, by name, it is a function (event handler) that unloads HTML. The event handlers that most beginners use are HTML event handlers. Here are some examples:

Example 1:

    <button onclick= "alert (' Success ')" > Point me </button>

This code is the event handler, click Button, will pop up the box, display success.

Features: The JavaScript code in the HTML event handler acts as the value of the onclick attribute, so we cannot use the non-escaped HTML syntax characters in the JavaScript code, such as & (and), "" (double quotes), < (less than sign) , > (greater than number) and so on. so the string in this example I used single quotes instead of double quotes. See below the use of non-escaped HTML syntax characters in JavaScript code.

Example 2:

    <button onclick= "alert (" Success ")" > Point me </button>

At this point, I used the HTML syntax character "" (double quotation marks) outside the success, this time will not pop up the window, but error syntax errors. but what if I still want to use double quotes? Instead, use the &quot; entity to replace the syntax characters in the HTML. as shown in the following example:

Example 3:

<button onclick= "alert (&quot;success&quot;)" > Point me </button>    <!--  Normal pop-up window--

In this example , we use HTML entities in JavaScript code without using HTML syntax characters, and then we don't get an error.

Example 4:

12345678 < button   Onclick= "Show ()" > Point I </ button > <!--  normal pop-up window-->  < script >       function show () {           alert ("Success"); &NBSP;&NBSP;&NBSP;&NBSP; </ script >

In this example we call the function and put the function definition in the script, which is also possible. Because: code in the event handler has access to any code in the global scope when it executes.  How do you understand this sentence? In fact, we can look at the scope chain of the button tag in chrome. As shown below:

Let's look at the scope where the script is located, as shown in:

You can see that the script tag is in the global scope.

That is, the HTML event handler in the current button is at the forefront of the scope chain, and the script is in the global scope, so the code in the event handler has access to any code in the global scope when it executes. This sentence is not difficult to understand.

Example 5:

    <button onclick= "alert (event.type)" > Point me </button>

The browser pop-up window displays: click. What does this example mean? Notice that I'm not event.type plus single quotes, which means it's not a string. In fact, eventis a local object--when an event on the DOM is triggered, an event object is generated that contains all the information about the event. and here is the type that pops up the object, that is, click.

Three disadvantages of the HTML event handler (emphasis):

1. Time difference problem . Because the user may start triggering the corresponding event at the beginning of the HTML element, it is possible that the script of the event (as in example 4, the function definition of the show () function in script) has not yet been loaded, and there is no execution condition at this time, so an error occurs.

WORKAROUND: Encapsulate the HTML event handler in a Try-catch block so that the error does not surface.

<input type= "button" value= "click Me" onclick= "try{show ();} catch (ex) {} >

2. The scope chain of the extended event instance program will cause different results in different browsers (example 4 I am the scope chain that I see in Chrome, which is not necessarily the case for other browsers, please note). Different JavaScript engines follow a slightly different identifier resolution rule, and there is a good chance that an error will occur when accessing unqualified object members.

3.HTML and JavaScript code are tightly coupled. The result: If you want to replace an event handler, you have to change two local--html code and JavaScript code.

So how to solve the above problem? The DOM0 level event handler is a good choice!

Part II: DOM0 Level Event handlers

  DOM0-level event handlers are also very common. I think it is the DOM0 level, and I believe that there is no DOM standard, and IE and Netscape Navigator both use the time processing program (I do not know whether it is reasonable, hope to criticize correct). Anyway, let's take a look at the following example.

Example 6:

    <button id= "button" > Dot me </button><script>    var button=document.getelementbyid ("button");    Button.onclick=function () {        alert ("clicked");    } </script>

that is, we first get a reference to the element in the script, and then assign a function to the OnClick event handler. as previously described, an event handler is a function, and button.onclick This form is the function as the method of the object. The object's method is that the event handler runs in the scope of the element (object) rather than in the global scope, because the method belongs to the object. ( Note: The event handler in Example 4 is running in the global scope.) If the This keyword exists in this function, this will point to the object. here we prove in the browser that the event handler is running in the scope of the element.

We see alert ("clicked"); it's actually running in the button.

We can also delete the event handlers specified by the DOM0-level method in the following way.

Button.onclick=null;

Through the above analysis we can know that the DOM0 level event handler is very good, it solves the HTML event handler three drawbacks: Time difference problem, the scope chain caused by different browser performance inconsistencies and HTML and JavaScript tightly coupled problem.

However, theDOM0 level event handler is not perfect , and it also has two drawbacks:

    1. We cannot add two events to an element at the same time.
    2. We cannot control the event flow of an element (capture or bubble).

For the second question, the first is an example of the following:

    <button id= "button" > Dot me </button><script>    var button=document.getelementbyid ("button");    Button.onclick=function () {        alert ("clicked");    }    Button.onclick=function () {        alert ("Again");    }

Although I set two event handlers for the same element, the end result is that only the second event is valid (overwriting the first event). Of course, humans are intelligent animals, DOM2-level events are a good solution to this problem!

Part III: DOM2 level Event handlers

The DOM2-level event handler defines two methods:

    • AddEventListener ()---Add event listeners
    • RemoveEventListener ()---Delete event listeners

 I mentioned the event handler, the event listener, at the beginning of the blog post . Both of these methods receive three parameters:

    1. The name of the event to be processed (note: Is the time name, so there is no on! ), such as Click, MouseOver, and so on.
    2. Functions as event handlers, such as function () {alert ("clicked");}
    3. A Boolean value that represents the way the event flows. false to invoke the event handler for the bubbling phase, and true to invoke the event handler for the capture phase. two kinds of stream of events in JavaScript can be seen for both bubbling and capturing time streams


The following two examples deepen the understanding of:

Example 7:

<button id= "button" > Dot me </button><script>    var button=document.getelementbyid ("button");    Button.addeventlistener ("click", Function () {        alert (this.id);    },false);    Button.addeventlistener ("click", Function () {        alert ("another event");    },false);</script>

result : First pop-up window: button.

Second pop-up window: another event.

conclusion : With the DOM2 level event handler, we can add two or more events to the same element. Events are triggered sequentially in order. And this also points to the current element, so the function executes within the scope of the element.

This analysis: like the previous DOM0-level event handlers, the AddEventListener here can also be seen as an object's method, except that DOM0-level methods require another function to assign values, The method here is predefined for the DOM2 level specification.

RemoveEventListener () This method of deleting an event handler is worth noting that an event handler that is added using AddEventListener () can only be removed by it and needs to pass in the same parameters.

Example 8:

    <button id= "button" > Dot me </button><script>    var button=document.getelementbyid ("button");    Button.addeventlistener ("click", Function () {        alert (this.id);    },false);    Button.removeeventlistener ("click", Function () {        alert ("another event");    },false);

The code above seems to remove the Click event handler, but the experiment proves that it is not possible because the event handler cannot be removed when it is an anonymous function . See the following examples of successful removal:

Example 9:

    <button id= "button" > Dot me </button><script>    var button=document.getelementbyid ("button");    function handler () {        alert (this.id);    }    Button.addeventlistener ("click", Handler,false);    Button.removeeventlistener ("click", Handler,false);</script>

  Successful removal!

Note: 1. The handler of the incoming method is not (), because this is all just defining the function, not the call, but it needs attention.

2. The third parameter of both methods is false, that is, the event handler is added to the bubbling phase. It is generally not true because the lower version of IE does not support the capture phase.

The DOM2 level event handler successfully resolves all previous event handlers and is perfect!!!! However, always maverick IE browser has a twist, it also has its own set of event handlers, let's take a look at it.

Part IV: IE event handlers

There are two methods in the IE event handler that resemble the DOM2 level event handlers:

    1. Attachevent ()
    2. DetachEvent ()

All of them receive two parameters:

    1. The event handler name. such as onclick, onmouseover, note: This is not an event, but the name of the event handler, so there is on.
    2. The event handler function. such as function () {alert ("clicked");}

there is no third parameter similar to the DOM2 level event handler because the bubbling event stream is only supported in IE8 and earlier versions.

 

  Attention:

The scope and DOM0 of an event handler for Attachevent () in a 1.IE event handler differs from DOM2, and her scope is in the global scope. Thus, unlike DOM0 and DOM2, this points to the element, this in IE points to the window.

2. Similarly, we can use Attachevent () to add multiple event handlers to the same element. However, unlike DOM2, the order in which events are triggered is not the order in which they are added, but the order in which they are added.

3. Similarly, event handlers that are added through attachevent () must be removed through the DetachEvent () method, and likewise, anonymous functions cannot be used.

4. browsers that support IE event handlers are not only IE browsers, but also opera browsers.

  

Part V: cross-browser event handlers

In fact, this part is seen as a cross-browser use, combining the previous sections together.

This section requires the creation of two methods:

    • AddHandler ()-This method is responsible for adding events, depending on the situation, using the DOM0, DOM2, and IE event handlers.
    • RemoveHandler ()-This method is to remove events added using AddHandler.

The two methods receive the same three parameters:

    1. The element to manipulate--gets through the DOM method
    2. Event name-note: Not on, such as Click, MouseOver
    3. Event handler function--that is, the handler function

The construction of these two methods is as follows:

var eventutil={    addhandler:function (element,type,handler) {        if (element.addeventlistener) {            Element.addeventlistener (Type,handler,false);///NOTE: The default is to use False (bubbling)        }else if (element.attachevent) {            Element.attachevent ("on" +type,handler);        } else{            element["on" +type]=handler;        }    ,    removehandler:function (element,type,handler) {        if ( Element.removeeventlistener) {            element.removeeventlistener (type,handler,false);///Note: false (bubbling)        is used here by default }else if (element.detachevent) {            element.detachevent ("on" +type,handler);        } else{            element["on" +type]=null;}}    ;

That is, first judge the DOM2 level event handler, then judge the IE event handler, and finally use the DOM0 level event handler.

Example: Use this example to construct the above method.

<! DOCTYPE html>

Finally, the browser successfully pops up "clicked".

Explore five types of event handlers in JavaScript

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.