JavaScript Learning Events

Source: Internet
Author: User
Tags event listener

1 Basic Concepts 1.1 events

The interaction between JavaScript and HTML is implemented through events.

  An event is a specific interaction moment that occurs in a document or browser window, in which handlers can be registered so that when an event occurs, the code in the handler is executed (the model corresponds to the Observer pattern in design mode).

1.2 Event Stream

The event flow describes the order in which events are accepted from the page.

2 Event Flow 2.1 event bubbling

  IE event flow is called event bubbling , that is, events begin to be accepted by the most specific elements, and then gradually propagate upward to less specific nodes.

Event bubbling can be supported by all browsers. Note that IE5.5 and earlier event bubbling skips the

2.2 Event Capture

Event capture is the earliest acceptance of an event by a less specific node , and the most specific element finally receives the event . Event capture is intended to capture an event before it reaches a predetermined target.

  event capture does not support older browsers, but both Ie9,firefox,chrome,opera and Safari currently support this event flow model .

2.3 DOM Event Flow

The DOM2 event flow consists of three phases: the event capture phase, the target stage, and the event bubbling phase ; In the DOM event flow, the actual target does not accept events during the capture phase (but IE9, Safari, Chrome, Firefox, and opera 9.5 and later will trigger events on the event object during the capture phase, i.e. there are two opportunities to manipulate events above the target object.

  DOM event streams are supported by both Ie9,firefox,chrome,opera and Safari, and DOM event streams are not supported in IE8 and earlier versions.

3 Event Handlers

An event is an action performed by the user or the browser itself, a common occurrence of which is click,focus,load, whereas a function that responds to an event is called an event handler (or event listener). The name of the event handler begins with "On", for example, the event handler for the Click event is the event handler for the Onclick,focus event that corresponds to the event handler for the Onfocus,load event, which is onload.

3.1 HTML event handlers

Each event supported by an HTML element can be specified with an HTML attribute with the same name as the corresponding event handler. The value of this attribute should be the JavaScript code that can execute. For example:

<input type= "button" value= "click Me" onclick= "showmessage ()"/>

There are two drawbacks to specifying an event handler in HTML:

First there is the problem of jetlag. If the corresponding event is triggered when an HTML element appears on the page, the event handler at the time may not yet have the execution condition. Specifically, in the example above, if the event handler ShowMessage is defined at the bottom of the page and the user clicks the button before the page resolves the function, an error is raised;

Another drawback is that such an extended event handler's chain of action causes different results in different browsers.

Another disadvantage of specifying an event handler through HTML is that the HTML and JavaScript code are tightly coupled. If you want to replace an event handler, you need to change two places at the same time: HTML code and JavaScript code.

3.2 DOM0 Level Event handlers

The traditional way to specify an event handler is to assign a function to an event handler property . Advantages of this approach: 1. Simple, 2. With cross-browser advantages. Specifying an event handler for an element is a two-step process:

(1) obtain a reference to the object to be manipulated;

(2) Set the event handler property of the element, such as the onclick, to a function. Examples are as follows:

<input type= "button" value= "click Me" id= "mybtn"/><script>var btn = document.getElementById (' mybtn '); Btn.onclick = function () {alert ("I am clicked!");} </script>

  the event handler specified with the DOM0-level method is considered to be the element's method , that is, the event handler runs in the scope of the element, at which point this refers to the current element .

Delete DOM0 Level event handler: Btn.onclick = null;

3.3 DOM2 Level Event handlers

The DOM2 level event defines two methods for handling the actions of the specified and deleted event handlers: AddEventListener () and RemoveEventListener (). Both methods accept three parameters: the event name to handle, the event handler function, and the Boolean value. Where a Boolean value of TRUE indicates that an event handler is called during the capture phase, otherwise the event handler is called during the bubbling phase.

  as with DOM0-level event handlers, DOM2-level event handlers are also run in the scope of the attached element. The benefit of adding an event handler using the DOM2-level method is that you can add multiple event handlers . Examples are as follows:

<input type= "button" value= "click Me" id= "mybtn"/><script>var btn = document.getElementById (' mybtn '); Btn.addeventlistener ("click", Function () {alert ("First");}, False); Btn.addeventlistener ("Click", Function () {alert ( "Second");}, False);</script>

After running, the content is "first" and "Second" dialog box, indicating that you can add multiple event handlers for the element through AddEventListener.

Event handlers added through AddEventListener () can only be removed by RemoveEventListener (), and the parameters passed in when they are removed are the same as those passed in at the time of the addition. Note Anonymous functions that are added by AddEventListener () cannot be removed .

<input type= "button" value= "click Me" id= "mybtn"/><script>var btn = document.getElementById (' mybtn '); Btn.addeventlistener ("click", Function () {alert ("First");}, False); Btn.removeeventlistener ("Click", Function () {// Invalidation: Deleting an anonymous function is not the same function as alert ("First"),}, False), var secondfunc = function () {alert ("Second");}; Btn.addeventlistener ("Click", Secondfunc, False); Btn.removeeventlistener ("Click", Secondfunc, false);// Success: Delete the same handler function </script>

After running, there is only one pop-up window, the content is "first", indicating that the second parameter must be guaranteed to be non-anonymous when using RemoveEventListener () to remove AddEventListener () to add an event handler function.

The addition of DOM2-level event handlers is mostly in the bubbling phase of events (the third parameter is false), which maximizes compatibility with various browsers.

  Ie9,firefox,chrome,opera and Safari support DOM2-level event handlers .

3.4 IE Event handlers

IE implements two methods similar to the one in the DOM: Attachevent () and DetachEvent (). Both methods accept the same two parameters: the event handler name and the event handler function. Because IE8 and earlier versions only support event bubbling, event handlers added through Attachevent () are added to the bubbling phase.

The main difference between using attachevent () in IE and using the DOM0-level method is the scope of the event handler, where the event handler runs at the global scope using the Attachevent () method, so this = = = Window.

Attachevent () Adds multiple event handlers, in reverse order of execution.

Events added using attachevent () can be removed by detachevent (), provided that the same parameters must be supplied. As with DOM methods, the added anonymous function cannot be removed.

Browsers that support IE event handlers have IE and opera.

3.5 cross-browser event handlers

To ensure that event handlers run consistently in most browsers, just focus on the bubbling phase.

var eventutil = {addhandler:function (element, type, handler) {if (Element.addeventlistener) {Element.addeventlistener ( Type, handler, false);} else if (element.attachevent) {element.attachevent ("on" + type, handler);} Else{element["on" + type] = Handler;}},removehandler:function (element, type, handler) {if (Element.removeeventlistener {Element.removeeventlistener (type, handler, false);} else if (element.detachevent) {element.detachevent ("on" + type, handler);} Else{element["on" + type] = null;}};
4 Event Object 4.1 Dom event object

Browsers that are compatible with the DOM (DOM0 and DOM2 levels) pass an event object into the events handler.

To prevent specific default behavior with the Preventdefault () method , immediately stop the propagation of the event in the DOM hierarchy with the Stoppropagation () method .

In an event handler, the object this is always equal to the value of Currenttarget, and Target contains only the actual target of the event .

4.2 IE Event Object

Unlike the event object accessed in the DOM, the event object in IE has several different ways, depending on how the event handler is specified.

When you add an event handler using the DOM0-level method, event exists as a property of the Window object, and if you add an event handler using attachevent (), Then there will be an event object that is passed in as an argument to the events handler (or you can access the event object through the Window object).

The event object for IE is contained in the properties and methods associated with creating it.

Where cancelbubble is set to True has the same effect as the Stoppropagation () method in the DOM;

ReturnValue set to False is the same as the Preventdefault () method in the DOM.

Srcelement represents the target of the event, as in the DOM in the target property.

Type is triggered with the same event types as the type attribute in the DOM.

4.3 Cross-Browser event objects

Add a method in the previous eventutil to handle the difference between the event objects in the DOM and IE (only the added code is shown below):

Getevent:function (event) {return event} event:window.event;},gettarget:function (event) {return Event.target | | even  T.srcelement;},preventdefalut:function (Event) {if (Event.preventdefalut) {event.preventdefalut ();  } else{Event.returnvalue = false;  }},stoppropagation:function (Event) {if (event.stoppropagation) {event.stoppropagation ();  } else{event.cancelbubble = true; }}

JavaScript Learning Events

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.