JavaScript Event Event Learning Chapter One event introduction _javascript skills

Source: Internet
Author: User
Tags support microsoft

No event, no script. Take a look at any Web page with JavaScript code: Almost every example has an event that triggers the script. The reason is very simple. JavaScript is adding internal activity to your page: the user does something and then the page responds.

So JavaScript needs a way to detect the user's actions and then know when to respond. It also needs to know that the function will be executed, and the function will do what you think is going to add to your page. These words describe how to write such a script. It's not easy, but it's a satisfying job.

When the user does something, the event happens, and some of the events are not directly triggered by the user: for example, the Load event triggers when the page is loaded.

JavaScript can detect some event. Starting with Netscape 2, it is possible to add an event Hanlder to the HTML element. These event handlers wait for a certain event, such as clicking on a link. When it happens, the event is executed through the JavaScript code you specify.

When the user makes an action, he triggers an event. When your code makes the page respond to the action, the interaction is generated.

History of an event handler

As mentioned, there is no need to add JavaScript to a page without an event handler. The best scripts are the ones that respond to the user's actions. So when Netscape released his second edition of JavaScript-enabled browsers, he also supported the event.

Netscape Mode

Netscape only supports a small number of events. The rapid popularity of mouseover and mouseout is the cool effect of returning to the original state when the mouse slides out of the picture while sliding. You can also see whether the user submits the form or resets the form, so that validation on the client is possible. The browser can also monitor one item of the form for gain or loss of focus or the page completes downloading or starts off. These are all very common things today, but at that time it was revolutionary. Because you can give feedback to the user's actions, the real interaction becomes possible.

The oldest form event handler looks like this. When the user clicks on the link, the event handler is executed and the dialog box pops up.

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

It is important to note that the oldest method of dealing with events is in fact the standard of Netscape. If you want JavaScript to work, other browsers, including IE, will have to comply with Netscape 2 and 3 's handling of the event standards. So these oldest event and event handlers work well in any JavaScript browser.

the current event pattern

However, the current event handlers have changed a lot compared to previous introductions. The first is a sharp increase in numbers. The method of registering an event handler for an HTML element also varies greatly. Can now be set entirely by JavaScript. No longer need a lot of attachment to the code, you can write some very simple code to set up all the event handlers.
The V4 browser also provides a lot of information about events. Where's the mouse? When did the incident occur? Did you press the keyboard? Eventually, the browser has to choose between an element and the parent element of the element to have an event handler for the same action. Which event triggers first?
As a result of this feature has exacerbated the war between browsers, Netscape and Microsoft developed a nearly incompatible two sets of event models. A third model has recently begun to appear, the DOM Event specification, published by the consortium. Although there is a serious flaw, the model is based on the old Netscape model but is more generalized and generic, it is a very outstanding work, add a lot of interesting functions, but also solve some of the old event model problems.
Since there are three models, event handlers cannot run in all browsers in the same way.

compatibility issues with browsers

Let's move on. Like DHTML,W3C DOM or other advanced scripting techniques, we have to be careful about every byte we buy. Using Stoppropagation () in IE or using srcelement in Netscape can cause serious errors that make our code useless. So we have to do the necessary checking of the browser's support before using the method or the attribute.
A simple code snippet is as follows:

Copy Code code as follows:

if (Netscape) {
Use Netscape model
}
else if (Explorer) {
Use Microsoft model
}


This is just the beginning of a solution. The number of event handlers that the nearest browser can run is huge, unless your code is not allowed to run in addition to Netscape or a few other browsers in IE.

All the niche browsers must support that event model with less glamorous decisions. Konqueror/safari are usually chosen strictly according to the standards of the consortium. Opera and icab usually support most of the old Netscape model and some of the Microsoft models. I haven't done research on any of the other smaller browsers.

But other smaller browsers may choose to support Microsoft's handling of events, as well as the properties of the web and old Netscape. None of this is a problem, anyway, they all support the model we know in their own way. Your code should be free of problems.

do not use browser type detection

First of all, never use browser detection, this is the shortest path to hell. Any code that uses navigator.useragent to do the detection of the event model, it's no use. You should just pull out and play JJ.
Second, do not be fooled by the event object detection of DHTML object detection. When you write DHTML, you usually detect the support of the DOM, such as if (document.all). If supported, the code can run well if it uses the Microsot all container.
However, DHTML and event handlers have different browser compatibility modes. For example, Opera 6 supports a part of the DOM of the consortium but does not support the Consortium event model. Therefore, the DHTML object Detection will make the wrong decision under opera. So code using if (document.layers) or other event model detection is not correct.

The right question

So what do 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 location is very troublesome, the other is relatively simple.
Also, it's best not to think about the three event models at all. In fact, we should understand the four event registration models, the two event execution models, and the two sequence of events. Here you can quickly view the list of event compatibility.
It sounds very complicated now, but it's not really like that. When we notice this, we should start to really understand the event handler. It's all about how to ask the right questions. Don't ask "How do I write the code for an event handler?" "Even if it's the right question, it's hard to answer-it takes 11 pages to make it clear." So you should ask specific questions that have specific answers:

"What's the matter here?" ”
"How do I register an event handler with an HTML element?"
"How do I prevent the default action from happening?" ”
"How do I access an event when I want to get more information?" ”
"When I succeeded in triggering the event, how do I read his attributes?" ”
"If an element and his parent element have an event handler for an event, who executes first?" ”

All of the above questions will be answered in a separate section.
The trick to writing 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 out event attributes.
Select an event registration model and then make sure that the event triggers in all browsers and then reads out the correct attributes and finally resolves the sequence of event triggers-if any. So you can solve the browser compatibility problem in DB to ensure that your code can run well in all browsers.

Go on

If you want to learn events in order, you should start reading the next chapter.

code to write an event handler

So how do you write the code for an event handler? In this chapter I will make a brief overview of the children's shoes in the hope of getting answers quickly and intending to learn theories later.

Registering 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 all times.
Here are four ways to register an event handler: INLINE,TRADITIONAL,W3C and Microsoft.
It is best to use the Traditinal method because he is good at Cross-browser and has great freedom and versatility. Register an event handler, as follows:
Copy Code code as follows:

Element.onclick = dosomething;
if (element.captureevents) element.captureevents (Event.click);


Now this function dosomething () is registered as an event handler for an HTML element click event. This means that whenever the user clicks on the element, dosomething () executes it.

access to this event

But you sign up for your event handler and you start writing real code. Usually you want to access the event itself, so you can read the information about the event.

Visit this event so you can read out his attributes, usually your event handler begins as follows:
Copy Code code as follows:

function DoSomething (e) {
if (!e) var e = window.event
E refers to the event
}


Now e represents the events in all browsers and you can also access this event.

Accessing this HTML element

Sometimes you want to be able to access the elements of the event that occurred. Here are two options: Use the This keyword or use the Target/srcelement property.

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

Copy Code code as follows:

function DoSomething (e) {
if (!e) var e = window.event
E refers to the event
This is refers to the HTML element which currently handles the event
Target/srcelement refer to the HTML element the event originally took
}


The Target/srcelement property contains a reference to the HTML element in which the initial event occurred. Very useful, but when the event is caught or bubbled up, he is still the element that initially happened and will not change.

Read Properties

The most difficult part of browser compatibility is reading out some interesting event properties. Learn the compatibility List and write your own code to get the information you need.
Make sure that you always use the most careful object checking. First determine if each attribute exists, and then read his value. Like what:
Copy Code code as follows:

function DoSomething (e) {
if (!e) var e = window.event
if (e.keycode) code = E.keycode;
else if (E.which) code = E.which;
}

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

Sequence of events

Finally, you need to decide if you want the event to bubble. If you don't want the event to bubble, stop him:
Copy Code code 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 for the event handler. The previous code and information will let you know when the event occurs and how your code should respond. Remember: Make the interaction more logical or your users won't understand what's going 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.