Without events, there is no script. Take a look at any web page that has JavaScript code: in almost every example there is an event that triggers the script. The reason is very simple. JavaScript is all about adding internal activity to your page: the user does something and the page responds.
So JavaScript needs a way to detect the user's actions and then know when to react. This also requires knowing which function will be executed, and the function will do some actions that you think will add color to your web page. These words describe how to write such a script. Although not easy, it is a very satisfying job.
The event occurs when the user does something. Of course, there are some events that will not be triggered directly by the user: for example, the load event will be triggered when the page is loaded.
JavaScript can detect some events. Starting with Netscape 2, it is possible to add event handlers to HTML elements. These event handlers wait for a certain event, such as clicking a link. When it occurs, the event will be executed through the JavaScript code you specify.
When the user takes an action, he triggers an event. Interaction occurs when your code causes the page to respond to this action.
History of Event Handlers
As mentioned above, there is no need to add JavaScript to the page without event handlers. The best scripts are those that react to user actions. Therefore, when Netscape released the second version of its browser that supported JavaScript, it also supported events.
Netscape mode
Netscape only supports a small set of events. Mouseover and mouseout quickly became popular because of the cool effect of changing the image when the mouse is rolled in and returning to the original state when the mouse is rolled out. And you can see whether the user has submitted the form or reset the form, so client-side verification becomes possible. The browser can also detect when an item in the form gains or loses focus or when the page completes downloading or begins to close. These are very commonplace things today, but at the time it was revolutionary. Because you can provide feedback to the user's actions, true 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 the dialog box pops up.
Notice this oldest way of handling events The fact that it's Netscape's standards is very important. If you want JavaScript to work, other browsers including IE have to follow the Netscape 2 and 3 event handling standards. So these oldest events and event handlers will work just fine in any JavaScript browser.
The current event mode
However, compared to the previous introduction, the current event handler has changed a lot. The first is the rapid growth in quantity. The method of registering event handlers for HTML elements has also changed significantly. Now fully configurable by JavaScript. Instead of having to hang on to a lot of code, you can write some very simple code to set up all the event handlers.
V4 browser also provides a lot of information about events. Where is the mouse? When did the incident occur? Is the keyboard pressed? Ultimately, the browser must make the choice that both an element and its parent element have event handlers for the same action. Which event triggers first?
Because of this feature, the war between browsers has intensified. Netscape and Microsoft have developed two sets of event models that are almost incompatible with each other. Recently a third model has begun to emerge, which is the DOM Event specification published by w3c. Although there is a serious flaw, the w3c model is based on the old Netscape model but is more generalized and general. It is a very outstanding work, adds a lot of interesting functions, and also solves some problems of the old event model.
Since there are three models, event handlers cannot run in the same way in all browsers.
Browser compatibility issues
Let’s continue. Just like DHTML, w3c DOM or other advanced scripting technologies, we must be careful about every byte we buy on behalf of others. Using stopPropagation() in IE or srcElement in Netscape will cause serious errors and render our code useless. Therefore, we must make necessary checks on browser support before using methods or attributes.
A simple code snippet is as follows:
if ( Netscape) {
use Netscape model
}
else if (Explorer) {
use Microsoft model
}
This is just the beginning of solving the problem. The number of event handlers that recent browsers can run is huge, unless your code doesn't allow a handful of browsers other than Netscape or IE to run.
All niche browsers must make the unglamorous decision to support that event model. Konqueror/Safari usually choose to strictly follow W3C standards. Opera and iCab generally support most older Netscape models and some Microsoft models. I haven't done any research on other, more niche browsers.
But other more niche browsers may choose to support Microsoft's method of handling events, while also having the attributes of W3C and old Netscape. There's nothing wrong with that, they all support the models we know in their own way. There should be no problem with your code.
Don’t use browser type detection First of all, never, ever use browser type detection, it’s a shortcut to hell. If any code uses navigator.userAgent to detect the event model, it is simply useless and should be pulled out directly.
Second, don’t be confused by the event object detection of DHTML object detection. When you write DHTML you usually check for DOM support, for example, if(document.all). If it is supported, then the code can run very well if it uses Microsoft's all container.
But DHTML and event handlers have different browser compatibility modes. For example, Opera 6 supports part of the W3C DOM but does not support the W3C event model. Therefore DHTML object detection will make wrong decisions under Opera. Therefore, it is incorrect for the code to use if(document.layers) or other event model detection.
The right question
So what do we do? The name of the Event property causes these problems. If we use different methods for specific object detection, we can basically solve 99% of browser incompatibility problems. Only the mouse position is very troublesome, everything else is relatively simple.
Also, it’s best not to think about those 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.
Now it sounds like it’s very complicated, but it’s not. When we notice this, we should start to truly understand event handlers. It's all about asking the right questions. Don't ask "How do I write the code for an event handler?" Even though it's the right question, it's hard to answer - it would take an 11-page article to explain. Therefore you should ask specific questions that have specific answers:
"What events are there?"
"How do I register an event handler for an HTML element?"
"How do I prevent it? What happens when the default action occurs? "
"How do I access an event when I want to get more information? "
" When I successfully trigger the event, how do I read its properties? ? ”
“If an element and its parent element both have event handlers for an event, who executes it first? ”
All the above questions will be answered in detail in separate chapters.
The trick to writing cross-browser event handlers is not to use the overall event model but to answer each question individually. You will find that you only need to consider browser compatibility issues when you need to read event properties.
First select an event registration model, then make sure that this event will be triggered in all browsers, then read the correct attributes, and finally solve the problem of event triggering order - if any. This way you can easily resolve browser compatibility issues and ensure your code runs well in all browsers.
Continue
If you want to learn the events in order, you should start reading the next chapter.
Write event handler code
So how to write event handler code? For those who want to get answers quickly and plan to learn theory later, I will give a brief overview in this chapter.
Register an event handler
The first step is to register your event handler. What you need to be sure of is that the browser will execute your code at all times.
There are four ways to register event handlers: inline, traditional, w3c and Microsoft.
It is best to use the traditinal method because it works well across browsers and has great freedom and versatility. Register an event handler as follows:
element.onclick = doSomething;
if (element.captureEvents) element.captureEvents(Event.CLICK);
Now this function doSomething() is registered as an event handler for the click event of the HTML element element. This means that whenever the user clicks on this element, doSomething() will be executed.
Access this event
But once you register your event handler you start writing the real code. Usually you want to access the event itself, so you can read the event's information.
To access this event so you can read out its properties, typically your event handler starts as follows:
function doSomething(e) {
if (!e) var e = window.event
// e refers to the event
}
Now e represents the event in all browsers, and you can also access this event.
Accessing this HTML element
Sometimes you want to be able to access the element where the event occurred. There are two ways here: use this keyword or use the target/srcElement attribute.
A safer 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 traditional mode.
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 where the event originally occurred. Very useful, but when the event is captured or bubbled, it remains the element where the event originally occurred and does not change.
Reading properties The problem of reading some interesting event properties (event properties) is the worst part of browser compatibility. Study this compatibility list, then write your own code to get the information you need.
Make sure to always use the most careful object inspection. First determine whether each attribute exists, and then read its value. For example:
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 key pressed and is compatible with all browsers.
Event order Finally, you need to decide if you want the event to bubble up. If you don’t want an event to bubble up, then block it:
function doSomething(e) {
if (!e) var e = window.event
// handle event
e.cancelBubble = true;
if (e.stopPropagation) e.stopPropagation( );
}
Writing Code
Now you can start writing the code for the event handler. Through the previous code and information, you can 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.