JavaScript Event Learning Chapter 1 Event Introduction

Source: Internet
Author: User
Tags support microsoft

There is no script without event. Take a look at any webpage with JavaScript code: almost all examples have an event that triggers the script. The reason is simple. JavaScript is to add internal activities to your page: the user does something and then the page responds.

Therefore, JavaScript requires a method to detect user actions before knowing when to respond. You also need to know that the function will be executed, and the function will perform some operations that you think will increase the color of your web page. These texts describe how to write such a script. Although not easy, it is a satisfying job.

When a user does something, the event will occur. Of course, some events will not be directly triggered by the user. For example, the load event will be triggered when the page is loaded.

JavaScript can detect some events. From Netscape 2, it is possible to add event hanlder to the HTML element. These event processing functions wait for a specific event, such as clicking a link. When it occurs, the event will be executed through the JavaScript code you specified.

When a user makes an action, it triggers an event. When your code allows the page to respond to this action, interaction is generated.

History of event handlers

As mentioned above, no event handler is necessary to add JavaScript on the page. The best scripts can respond to user actions. Therefore, when Netscape releases its second version that supports JavaScript browsers, it also supports event.

Netscape Mode

Netscape only supports a small number of events. In the fast fashion of Mouseover and mouseout, when the mouse slides and the image slides out, the system returns to the original status. In addition, you can see whether the user submitted the form or reset the form, so that the verification on the client becomes possible. The browser can also monitor an item of the form to obtain or lose the focus, download the page, or close it. These are common things, but they were revolutionary at that time. Because you can give feedback on user actions, real interaction becomes possible.

The event handler in the oldest form looks like this. When the user clicks the link, the event handler is executed and a dialog box is displayed.

<A href = "somewhere.html" onclick = "alert ('I \ 've been clicked! ') ">

It is noted that the oldest method of event processing is actually the Netscape standard and is very important. To work with JavaScript, other browsers, including IE, must comply with the event handling standards of Netscape 2 and 3. Therefore, these oldest events and event handlers can run well in any JavaScript browser.

Current Event Mode

However, compared with the previous introduction, the event processing program has changed a lot. The first is the sharp increase in the number. The method for registering the event handler for HTML elements is also greatly changed. It is now completely configurable by JavaScript. You no longer need to attach a large amount of code to it. You can write some simple code to set all the event handlers.
The V4 browser also provides a lot of information about events. Where is the mouse? When will an event occur? Is the keyboard pressed? In the end, the browser must select an event handler for each action of an element and its parent element. Which event is triggered first?
Because of this feature, the war between browsers has been intensified. Netscape and Microsoft have developed two event models that are almost incompatible with each other. The third model has recently become apparent, DOM Event specification released by w3c. Although there is a serious defect, the w3c model is based on the old Netscape model, but it is more widely and universally used. This is an outstanding work and many interesting functions are added, it also solves some problems existing in the old event model.
Since there are three models, the event handler cannot run in all browsers in the same way.

Browser compatibility

Let's continue. Just like DHTML, w3c DOM, or other advanced script technology, we need to be careful with every byte we buy on behalf. Using stopPropagation () in IE or srcElement in Netscape will cause serious errors and make our code useless. Therefore, before using methods or attributes, we must check the browser's support.
A simple code snippet is as follows:
Copy codeThe Code is as follows:
If (Netscape ){
Use Netscape model
}
Else if (Explorer ){
Use Microsoft model
}


This is just the beginning to solve the problem. The number of Event Handlers that can run in the nearest browser is huge, unless your code cannot run in a few browsers except Netscape or IE.

All niche browsers must make less brilliant decisions to support the event model. Konqueror/Safari is usually executed in strict accordance with W3C standards. Opera and iCab usually support most of the old Netscape models and some Microsoft models. I have not studied other smaller browsers.

However, other smaller browsers may choose to support Microsoft's event handling methods, and have W3C and old Netscape attributes. There is no problem with this. In short, they all use their own methods to support the models we know. Your code should be fine.

Do not use browser type detection

First, never use browser detection, which is a shortcut to hell. If any code uses navigator. userAgent for event model detection, it is useless and should be pulled out directly to play JJ.
Second, do not be confused by DHTML's object detection event object detection. When writing DHTML, you usually check DOM support, such as if (document. all ). If yes, the code can run well if the Microsot all container is used.
However, DHTML and event handlers have different browser compatibility modes. For example, Opera 6 supports part of W3C DOM but does not support W3C event model. Therefore, DHTML Object detection may make incorrect decisions under Opera. Therefore, it is incorrect for the code to use if (document. layers) or other event models for detection.

Correct question

So what should we do? The name of the Event attribute causes these problems. If we use different methods for specific object detection, we can basically solve the incompatibility problem of 99% of browsers. Only the mouse position is very troublesome, and others are relatively simple.
In addition, it is best not to think about the three event models at all. In fact, we should understand four event registration models, two event execution models and two event sequences. Here you can quickly view the event compatibility list.
It seems very complicated now, but it is not actually like this. When we notice this, we should begin to really understand the event handler. This is all about how to raise the correct question. Do not ask "How do I write the code of the event handler ?" Even if this is a correct question, it is hard to answer-it takes 11 pages of long articles to be clear. Therefore, you should ask specific questions with specific answers:

"What events are there here ?"
"How can I register an event handler for an HTML element ?"
"How can I prevent the occurrence of default actions ?"
"How can I access an event when I want more information ?"
"When I successfully trigger an event, how can I read its attributes ?"
"If an element and its parent element have an event handler for an event, who will execute it first ?"

All the questions above will be answered in a separate chapter.
The trick to write cross-browser Event Handlers is not to use the overall event model but to answer each question separately. You will find that you only need to consider browser compatibility issues when you need to read the event attributes.
First select an event registration model, then confirm that the event will be triggered in all browsers, then read the correct attributes, and finally solve the event trigger sequence problem-if any. In this way, you can solve the browser compatibility problem and ensure that your code can run well in all browsers.

Continue

If you want to learn events in sequence, you should start to read the next chapter.

Code for writing event handlers

So how do I write the code of the event handler? In order to quickly get answers and plan to learn more about the theory, I will give a brief overview in this chapter.

Register an event handler

The first step is to register your event handler first. You need to be sure that the browser will execute your code at any time.
There are four methods to register an event handler: inline, traditional, w3c, and Microsoft.
It is best to use the traditinal method, because it can be good cross-browser and has great freedom and versatility. Register an event handler as follows:
Copy codeThe Code is as follows:
Element. onclick = doSomething;
If (element. captureEvents) element. captureEvents (Event. CLICK );


Now this function doSomething () is registered as an event handler for the HTML element click event. This means that doSomething () will be executed no matter when the user clicks this element.

Access this event

But after you register your event handler, you start to write code. You usually want to access the event itself, so you can read the event information.

To access this event, you can read its attributes. Generally, your event handler starts as follows:
Copy codeThe Code is as follows:
Function doSomething (e ){
If (! E) var e = window. event
// E refers to the event
}


Now e indicates the event in all browsers. You can also access this event.

Access this HTML Element

Sometimes you want to access the elements of an event. There are two methods: Use the this keyword or use the target/srcElement attribute.

The safe way to access HTML elements is to use the this keyword. This does not always point to the correct HTML element, but works well with the traditional mode.

Copy codeThe Code is as follows:
Function doSomething (e ){
If (! E) var e = window. event
// E refers to the event
// This refers to the HTML element which currently handles the event
// Target/srcElement refer to the HTML element the event originally took place on
}


The target/srcElement attribute contains a reference to the HTML element of the initial event. It is very useful, but when the event is captured or bubbling, it is still the element of the initial event that will not change.

Read attributes

Reading interesting event properties is the worst part of browser compatibility. Learn the compatibility list and write your own code to get the information you need.
Always use the most careful object check. First, determine whether each attribute exists and then read its value. For example:
Copy codeThe Code is as follows:
Function doSomething (e ){
If (! E) var e = window. event
If (e. keyCode) code = e. keyCode;
Else if (e. which) code = e. which;
}

Now the code includes the key pressed and is compatible with all browsers.

Event Sequence

Finally, you need to decide whether you want the event to bubble up. If you do not want event bubbling, stop it:
Copy codeThe Code is as follows:
Function doSomething (e ){
If (! E) var e = window. event
// Handle event
E. cancelBubble = true;
If (e. stopPropagation) e. stopPropagation ();
}


Write code
Now you can start writing the code of the event handler. With the previous Code and information, you can know when an event occurs and how your code responds. Remember: make interaction more logical, or your users will not understand what happened.

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.