Interaction between JavaScript and HTML

Source: Internet
Author: User

The interaction between JavaScript and HTML is implemented through events. JavaScript uses an asynchronous event-driven programming model. When a document, browser, element, or related object occurs, the browser generates an event. If JavaScript focuses on specific types of events, it can register the handle to be called when such events occur.

Event stream

The event stream describes the sequence of events received from the page. For example, if there are two nested divs and the inner div is clicked, is the inner div first triggered by the click event or the outer layer first? There are currently three main models

IE event bubbling: the event is received by the most specific element at the beginning, and then spread to a more specific element step by step.

Event capture in Netscape: events are received earlier on a node that is not specific, and events are received at the end of the most specific element, which is opposite to event bubbles.

DOM event stream: DOM2-level events stipulate that the event stream consists of three phases: Event capture stage, which is in the target stage and event bubble stage. Event capture occurs first, which provides an opportunity to intercept events, then the actual target receives the event, and finally the bubble sentence stage.

Opera, Firefox, Chrome, and Safari all support DOM Event streams. IE does not support event streams, but only supports event bubbles.

If you have the following html, click the div Area

Copy codeThe Code is as follows: <! DOCTYPE html>
<Html>
<Head>
<Meta http-equiv = "Content-type" content = "text/html; charset = UTF-8"/>
<Title> Test Page </title>
</Head>
<Body>
<Div>
Click Here </div>
</Body>
</Html>

Event handler)

We also call it an event listener (listener). An event is an action performed by a user or a browser. For example, click, load, moseover, and so on are all event types (commonly known as event names). The method to respond to an event is called an event handler, event listener, or event handle, the name of the event handler is on + event type.

After learning about this, let's see how to add an event handler to the element.

Each event supported by the HTML event handler element can be specified using an HTML attribute with the same name as the corresponding event handler. The value of this attribute should be executable JavaScript code. We can add a click event handler for a button.

Copy codeThe Code is as follows: <input type = "button" value = "Click Here" onclick = "alert ('clicked! '); "/>

The HTML event handler can contain the specific action to be executed, or call the script defined elsewhere on the page. The preceding example can be written as follows:

Copy codeThe Code is as follows: <input type = "button" value = "Click Here" onclick = "showMessage ();"/>
<Script type = "text/javascript">
Function showMessage (){
Alert ('clicked! ');
}

It is convenient to specify the event handler in HTML, but there are two disadvantages.

First, there is a loading order problem. If the event handler loads after html code, You may click a trigger event such as a button before the event handler completes loading. There is a time difference problem.

Second, html code and JavaScript code are closely coupled, making maintenance inconvenient.

JavaScript specifies that the event handler uses JavaScript to specify the event handler, which is to assign a method to the event handler attribute of an element. Each element has its own event handler attributes. These attributes are usually named in lower case, such as onclick. If you set the values of these attributes to a method, you can specify the event handler as follows:

Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
BtnClick. onclick = function showMessage (){
Alert (this. id );
};
</Script>

In this way, the event handler is considered an element method, and the event handler runs under the element scope. this is the current element. Therefore, click the button and the result is btnClick.

In this way, we can delete the event handler by assigning the onclick attribute of the element to null.

DOM2 event handler DOM2-level events define two methods for processing specified and deleted Event Handlers: addEventListener and removeEventListener. All DOM nodes contain these two methods, and they all accept three parameters: event type, event processing method, and a Boolean value. If the Boolean parameter is true, the event handler is called in the capture phase. If the Boolean parameter is false, the event is processed in the event bubbling phase.

We can write the example just now.

Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
BtnClick. addEventListener ('click', function (){
Alert (this. id );
}, False );
</Script>

The code above adds the click event handler for the button, which is triggered in the bubble stage. Like the previous method, this program runs in the element scope, but it has a benefit, we can add multiple handlers for the click event.Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
BtnClick. addEventListener ('click', function (){
Alert (this. id );
}, False );
BtnClick. addEventListener ('click', function (){
Alert ('Hello! ');
}, False );
</Script>

In this way, the two event handlers are executed sequentially after the user clicks the button.

The event handler added through addEventListener can only be removed through removeEventListener, and the parameters are the same as those added during removal. This means that the added anonymous function cannot be removed, although the method bodies of anonymous functions are the same, but the handles are different, you can write this when you remove an event handler.

Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
Var handler = function (){
Alert (this. id );
}
BtnClick. addEventListener ('click', handler, false );
BtnClick. removeEventListener ('click', handler, false );
</Script>

The following are the general questions about IE compatibility...

IE does not support addEventListener and removeEventListener methods, but implements two similar methods: attachEvent and detachEvent. Both methods receive two identical parameters, including the event handler name and event handler method, because IE supports event bubbling, the added program will be added to the bubble stage.

You can add an event handler using attachEvent as follows:

Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
Var handler = function (){
Alert (this. id );
}
BtnClick. attachEvent ('onclick', handler );
</Script>

The result is undefined, which is very strange. We will introduce it later.

The event handler added by using attachEvent can be removed through detachEvent. The conditions are the same and anonymous functions cannot be removed.

Copy codeThe Code is as follows: <input id = "btnClick" type = "button" value = "Click Here"/>

<Script type = "text/javascript">
Var btnClick = document. getElementById ('btnclick ');
Var handler = function (){
Alert (this. id );
}
BtnClick. attachEvent ('onclick', handler );
BtnClick. detachEvent ('onclick', handler );
</Script>

Cross-browser event handlers

We can see that in different browsers, the methods for adding and removing event handlers are different. To write cross-browser event handlers, first, we need to know the differences between Processing Event Handlers in different browsers.

There are several differences between addEventListener and attachEvent when adding event handlers
1. the number of parameters is different. This is the most intuitive one. addEventListener has three parameters. attachEvent has only two parameters. The event handler added by attachEvent can only occur in the bubble stage, the third parameter of addEventListener determines whether the added event handler is processed in the capture or bubble phase (we generally set it to the bubble phase for browser compatibility)

2. The first parameter has different meanings. The first parameter of addEventListener is the event type (such as click and load), while the first parameter of attachEvent specifies the name of the event processing function (onclick, onload)

3. the scope of the event handler is different. The scope of the addEventListener is the element, and this is the trigger element. The attachEvent event handler runs in the global variable, and this is the window, so the undefined is returned in the example, instead of the element id.

4. when multiple event handlers are added to an event, the execution sequence is different. The addEventListener is added in the order of addition, however, when attachEvent adds multiple event handlers, the order is irregular (when there are few adding methods, most of them are executed in reverse order in the order of adding, but when there is more to add, there will be no regularity ), therefore, when adding multiple functions, it is better not to rely on the execution sequence. If it depends on the function execution sequence, it is best to handle it by yourself. Do not count on the browser.

After understanding the four differences, we can try to write a method for adding an event handler with better browser compatibility.

Copy codeThe Code is as follows: function addEvent (node, type, handler ){
If (! Node) return false;
If (node. addEventListener ){
Node. addEventListener (type, handler, false );
Return true;
}
Else if (node. attachEvent ){
Node. attachEvent ('on' + type, handler ,);
Return true;
}
Return false;
}

In this way, we first solve the problem where the number of parameters is different. Now the three parameters are triggered in the event bubble phase, and the second problem is also solved. If it is IE, we add on to type. There is no solution for the fourth problem. You need to pay attention to it. In general, we will not add many event handlers, it feels good to try this method, but we have not solved the third problem. Because the processing program has different scopes, if the handler has such operations as this, it will cause errors in IE, in fact, most functions have this operation.

Copy codeThe Code is as follows: function addEvent (node, type, handler ){
If (! Node) return false;
If (node. addEventListener ){
Node. addEventListener (type, handler, false );
Return true;
}
Else if (node. attachEvent ){
Node. attachEvent ('on' + type, function () {handler. apply (node );});
Return true;
}
Return false;
}

In this way, we can solve this problem, but the new problem comes again. We have added an anonymous event handler and cannot use detachEvent to cancel the event handler, there are many solutions that we can use to learn from the master's processing method. The founder of jQuery, John Resig, is doing this.

Copy codeThe Code is as follows: function addEvent (node, type, handler ){
If (! Node) return false;
If (node. addEventListener ){
Node. addEventListener (type, handler, false );
Return true;
}
Else if (node. attachEvent ){
Node ['E' + type + handler] = handler;
Node [type + handler] = function (){
Node ['E' + type + handler] (window. event );
};
Node. attachEvent ('on' + type, node [type + handler]);
Return true;
}
Return false;
}

When canceling the event processing program

Copy codeThe Code is as follows: function removeEvent (node, type, handler ){
If (! Node) return false;
If (node. removeEventListener ){
Node. removeEventListener (type, handler, false );
Return true;
}
Else if (node. detachEvent ){
Node. detachEvent ('on' + type, node [type + handler]);
Node [type + handler] = null;
}
Return false;
}

John Resig cleverly utilizes the closure and looks good.

Event object

An event object is generated when an event on the DOM is triggered. This object contains all event-related information, including the elements and types of events. All browsing operations support event objects, but the supported methods are different.

The event object in the DOM is compatible with the DOM, and an event object is generated in the event handler. Apply the addEvent method we just wrote

Copy codeThe Code is as follows: var btnClick = document. getElementById ('btnclick ');
AddEvent (btnClick, 'click', handler );

When you click the button, we can see that the pop-up content is the click pop-up window.

The event object contains the attributes and methods related to the specific events that you create. The types of triggering events are different, and the available attributes and methods are different. However, all events contain

Attribute/Method

Type

Read/write

Description

Bubbles Boolean Read-Only Event bubble?
Cancelable Boolean Read-Only Can I cancel the default event behavior?
CurrentTarget Element Read-Only Current processing element of the event handler
Detail Integer Read-Only Event-related details
EventPhase Integer Read-Only Event Handler stage: capture stage, target stage, and bubble stage
PreventDefault () Function Read-Only Cancel default event Behavior
StopPropagation () Function Read-Only Cancel event further capture or bubble
Target Element Read-Only Event target Element
Type String Read-Only Event Type triggered
View AbstractView Read-Only The abstract view associated with the event is equivalent to the window object in which the event occurs.

In the event handler, this is always equivalent to currentTarget, and target is the actual target of the event.

To prevent default events, you can use the preventDefault () method, provided that the cancelable value is true. For example, we can block the default behavior of link navigation.

Copy codeThe Code is as follows: document. getElementsByTagName ('A'). onclick = function (e ){
E. preventDefault ();
}

The stopPaopagation () method can stop the propagation of events at the DOM level, that is, cancel further event capture or bubble. We can call stopPropagation () in the event handler of the button to avoid the occurrence of events registered on the body.

Copy codeThe Code is as follows: var handler = function (e ){
Alert (e. type );
E. stopPropagation ();
}
AddEvent (document. body, 'click', function () {alert ('clicked body ')});
Var btnClick = document. getElementById ('btnclick ');
AddEvent (btnClick, 'click', handler );

If you comment out e. stopPropagation (); when you click a button, the click Event of the body will also be triggered due to event bubbling, but after you call this sentence, the event will stop spreading.

There are several different ways for the event object in IE to access the event object in IE, depending on the method of the specified event handler. When an event handler is directly added to the DOM element, the event object exists as an attribute of the window object.

Copy codeThe Code is as follows: var handler = function (){
Var e = window. event;
Alert (e. type );
}
Var btnClick = document. getElementById ('btnclick ');
BtnClick. onclick = handler;

We obtained the event object through window. event and detected its type. However, if the event handler is added through attachEvent, an event object will be passed into the event handler.

Copy codeThe Code is as follows: var handler = function (e ){
Alert (e. type );
}
Var btnClick = document. getElementById ('btnclick ');
AttachEvent (btnClick, handler );

Of course, you can also access the event through the window object at this time. For convenience, we usually pass in the event object. All the events in IE include the following attribute methods:

Attribute/Method

Type

Read/write

Description

CancelBulle Boolean Read/write The default value is false. If it is set to true, event bubbles can be canceled.
ReturnValue Boolean Read/write The default value is true. If it is set to false, the default event behavior can be canceled.
SrcElement Element Read-Only Event target Element
Type String Read-Only Event Type triggered

Cross-browser event objects, although DOM and IE event objects are different, based on their similarity, we can still write cross-browser event object solutions.

Copy codeThe Code is as follows: function getEvent (e ){
Return e | window. event;
}

Function getTarget (e ){
Return e.tar get | e. scrElement;
}

Function preventDefault (e ){
If (e. preventDefault)
E. preventDefault ();
Else
E. returnValue = false;
}

Function stopPropagation (e ){
If (e. stopPropagation)
E. stopPropagation ();
Else
E. cancelBubble = true;
}

Common HTML events

There are some HTML events that we will often use. These events are not necessarily related to user operations. Here is just a simple reference. For detailed usage, you have to go to Baidu Google.

1. load: When the page is fully loaded, it is triggered on the window. When the image is loaded, it is triggered on the img element, or when the embedded content is loaded, it is triggered on the object element.
2. unload: triggered on the window after the page is fully uninstalled, or after the embedded content is uninstalled, triggered on the object element.
3. select: triggered when the user selects characters in the text box.
4. change: triggered when the value of the text box changes after the focus of the text box changes
5. submit: triggered when a user submits a form
6. resize: triggered when the window or frame size changes
7. scrool: triggered when you scroll an element with a scroll bar
8. focus: triggered on the window and corresponding elements when the page or element obtains the focus.
9. blur: triggered on the window and corresponding elements when the page or element loses focus
10. beforeunload: triggered on the window before page uninstallation
11. mousewheel: it is not HTML. It is triggered when you use the scroll wheel to interact with the page and scroll the page vertically.

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.