search
HomeWeb Front-endJS TutorialJavaScript Event Event Learning Chapter 1 Introduction to Event_javascript skills

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:

Copy code The code 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:
Copy code The 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 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:
Copy code The code is 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.

Copy code The 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 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:
Copy code The 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;
}

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:
Copy the code The code is as follows:

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.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.