search
HomeWeb Front-endJS TutorialJavaScript Event Learning Chapter 4 Traditional Event Registration Model_javascript skills

Registering events in the oldest JavaScript browsers is only possible through inline mode. Since DHTML fundamentally changes the way you manipulate pages, event registration must be extensible and highly adaptable. So there must be a corresponding event model. Netscape started with the third generation of browsers, and IE started with the fourth generation of browsers.
Because Netscape 3 began to support this new event registration model, it was the de facto standard before the browser wars. Therefore, Microsoft had to make concessions on compatibility for the last time for the countless pages on the Internet that use the Netscape event processing model.
So these two browsers, in fact all browsers support the following code:

Copy code Code As follows:

element.onclick = doSomething;

This is the best way to register an event. Whenever the user clicks on this HTML element, doSomething() will be executed. This is the only best way to register events across browsers, and it's important to have a deep understanding of this model and its limitations.
Because there is no official standard, I temporarily call it the traditional event registration model. At the same time, w3c has also standardized event registration, and Microsoft has also launched an advanced mode, but the traditional mode can still run well.


Advanced Event Register
Starting from Netscape 3/IE 4, JavaScript is able to recognize the attributes of a series of events on an element. Most HTML elements have onclick, onmouseover, onkeypress and other attributes. What attributes those elements have—which elements support which events—all depend on the browser.
These properties are nothing new to themselves either. It already exists in the oldest JavaScript browsers.
Copy code The code is as follows:


The A tag here has an onclick parameter, which becomes an attribute of the A element in JavaScript. Event handlers in older browsers could only be registered by setting parameters on elements in the page source code. If you want this script to be executed on all A tags, then you need to add onclick events to all links.
With the arrival of the traditional event registration model, these onclick, onmouseover or other event processing of HTML elements can be registered through JavaScript. Now you can add, modify, or remove event handlers without touching a single bit of HTML. When you access HTML elements through the DOM, you can write code like this:
Copy code The code is as follows:

element.onclick = doSomething;


Now our example function doSomething() is registered on the onclick attribute of the element element, and when the user clicks This element function will be executed. Note that event names must be lowercase.
To delete this event handler, simply leave the click event empty:
Copy the code The code is as follows:

element.onclick = null;

The event handler is the same as a normal JavaScript function. He can perform it even when the event has not occurred. If you write like this:
Copy code The code is as follows:

element.onclick()

Then doSomething will be executed as well. Although if it is a function that doesn't know what to do or generates an error, no real event occurs. So this is a rarely used method of executing event handlers.
Microsoft's IE5.5 and higher versions of IE also have a fireEvent() method to accomplish the same thing. Use as follows:
Copy code The code is as follows:

element.fireEvent('onclick')


No brackets
Note that you cannot use brackets when registering an event handler. The onclick method will be set to another function. If you write like this
Copy the code The code is as follows:

element.onclick = doSomething();


Then this function will be executed and its result will be registered to onclick. This is not what we expect, we just want the function to execute when the event occurs. In addition, the function is written to be executed when the event occurs. If there is no associated execution, it will cause serious confusion and errors.
So we copy the entire doSomething() method in the event handler. We just want to execute this function when the event is executed.


this
In JavaScript, the this keyword usually refers to the owner of the function. If this points to the HTML element where the event occurred, then everything is fine and you can do a lot of things easily.
Unfortunately, although this is very powerful, it is still difficult to use if you don't know exactly how it works. I've discussed this in detail elsewhere, but here I'll give an overview in traditional mode.
In traditional mode this works as follows; note that this is slightly different from inline mode. Now the this keyword is in the function, not in the HTML parameter. This difference will be discussed separately later.
Copy code The code is as follows:

element.onclick = doSomething;
another_element.onclick = doSomething;
function doSomething() {
this.style.backgroundColor = '#cc0000';
}

If you register doSomething() as any HTML element click event, then when the user clicks on that element, the element will get a background.


Anonymous functions
Suppose you want all divs to change the background color when the mouse passes over it, and then return to the background color when the mouse leaves. To use this correctly, you can write like this:
Copy the code The code is as follows:

var x = document.getElementsByTagName('DIV');
for (var i=0;i x[i].onmouseover = over;
x[i ].onmouseout = out;
}

function over() {
this.style.backgroundColor='#cc0000'
}

this.style.backgroundColor='#ffffff'
}



These codes will run, no problem. But since over() and out() are relatively simple, you can use a more elegant anonymous function method to write:
Copy code The code is as follows:

for (var i=0;ix[i].onmouseover = function () {
this.style.backgroundColor='#cc0000'}
x[i].onmouseout = function () {
this.style.backgroundColor='#ffffff'}
}

Anyway, onmouseover and onmouseout both get a function. Rather than copying over() and out(), it is better to define an event handler directly on the script where the event is registered. Since these functions have no names, they are anonymous functions.
These two methods of registering event handlers are basically the same, the only difference is that the second one has less code. I really like anonymous functions and I use them when registering a simple event handler.


Problem
A small problem is that the onclick attribute can only contain one function in traditional mode. The problem arises when you want to register multiple event handlers for an event.
For example, you have written a draggable module. This module is registered on the onclick event handler so you can start dragging when you click on it. You also wrote a module that can track user clicks and send information to the server during onunload, so that you can know how your page is used. This module also needs to register an onclick event on the element.
So it might look like this:
Copy the code The code is as follows:

element. onclick = startDragDrop;
element.onclick = spyOnUser;

This is where an error occurs. The second registration procedure will overwrite the first one, so only spyOnUser() will be executed when the user clicks on the element.
The solution is to register a method containing two methods:
Copy the code The code is as follows:

element.onclick = function () {
startDragDrop();
spyOnUser()
}



Flexible registration
But Let’s assume you don’t use two modules on every page of your website. If you still write like this:
Copy code The code is as follows:

element.onclick = function ( ) {
startDragDrop();
spyOnUser()
}

You will get an error message because one of the functions is undefined. So be especially careful when registering events. When we want to register spyOnUser() when startDragDrop() may have already been registered, then we can write like this:
Copy code The code is as follows:

var old = (element.onclick) ? element.onclick : function () {};
element.onclick = function () {
old();
spyOnUser()
};

First you define a variable old. If the element already has an onclick event handler, store it in old. If not, set old to an empty function. Now you need to register a new event handler for a div. Then the program will first execute old(), and then execute spyOnUser(). Now the new event handler is added to the element, and the previously registered event handlers (if any) are also included.
Last question: What if you want to remove one of the event handlers? Now I'm not sure. You need to edit element.onclick() via some method, I haven't looked into this yet.
Other modes
We see that the traditional mode is very simple and easy to use, but the solution when you add several programs to an event is still ugly. W3C's event handler solves this problem very well.
Continue
If you want to continue learning, please read the next chapter.
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
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.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version