JavaScript Advanced Programming---Event object

Source: Internet
Author: User
Tags event listener tagname

An event is an implementation of asynchronous programming that is essentially a specific message passed between the various components of a program.

DOM event operations (listening and triggering) are defined on the Eventtarget interface

  The interface is three methods, AddEventListener and RemoveEventListener are used to bind and remove the listener function, dispatchevent is used to trigger the event.

AddEventListener ()

A listener function that defines a specific event on the current node or object.

Target.addeventlistener (Type, listener[, Usecapture]);

The AddEventListener method accepts three parameters.

    • Type, event name, case insensitive.

    • Listener, the listener function. Specifies that the listener function is called when an event occurs.

    • Usecapture, whether the listener is triggered during the capture phase. This parameter is a Boolean value that defaults to False (indicating that the listener function is only triggered during the bubbling phase). The old browser specifies that the parameter must be written, and the newer version of the browser allows this parameter to be optional. In order to maintain compatibility, it is recommended to always write this parameter.

function Hello () {  console.log (' Hello World ');} var button = document.getElementById ("btn"); Button.addeventlistener (' Click ', Hello, false);

In the above code, the AddEventListener method is the button node, which binds the listener function of the click event Hello, which is only triggered during the bubbling phase.

You can use the AddEventListener method to add multiple listener functions for the same event of the current object. These functions are triggered by the order in which they are added, which is triggered first. If you add the same listener multiple times for the same event, the function executes only once, and the extra additions are automatically removed (you do not have to use the RemoveEventListener method to manually remove them).

  

function Hello () {  console.log (' Hello World ');} Document.addeventlistener (' Click ', Hello, false);d Ocument.addeventlistener (' Click ', Hello, false);

Executing the above code, clicking on the document will only output one line of "Hello World".

If you want to pass parameters to the listener function, you can wrap the listener function with an anonymous function.

function print (x) {  console.log (x);} var el = document.getElementById ("Div1"); El.addeventlistener ("Click", Function () {print (' Hello ')}, False);

The above code passes an anonymous function, passing a parameter to the Listener function print.

RemoveEventListener ()

Used to remove the event listener function added by the AddEventListener method.

Div.addeventlistener (' Click ', Listener, False);d Iv.removeeventlistener (' Click ', Listener, false);

The parameters of the RemoveEventListener method are exactly the same as the AddEventListener method. It is not sensitive to the first parameter "event Type", which is also case-insensitive.

Note that the listener function that the RemoveEventListener method removes must be exactly the same as the parameters of the corresponding AddEventListener method, and is not valid at the same element node.

Dispatchevent ()

The Dispatchevent method triggers the execution of the listener function by triggering the specified event on the current node. The method returns a Boolean value that, if one of the listener functions is called Event.preventDefault() , returns a value of false, otherwise true.

Target.dispatchevent (event) The argument to the Dispatchevent method is an instance of an event object. Para.addeventlistener (' Click ', Hello, false); var event = new Event (' click ');p ara.dispatchevent (event);

If the parameter of the Dispatchevent method is empty, or if it is not a valid event object, an error is expected.

The following code determines whether the event was canceled, based on the return value of the Dispatchevent method.

var canceled =!cb.dispatchevent (event);  if (canceled) {    Console.log (' event cancellation '),  } else {    Console.log (' event not canceled ');}  }

  

Listener functions

The Listener function (listener) is the function that the program executes when the event occurs. It is the main programming mode of the event-driven programming pattern.

The DOM provides three methods that you can use to bind listener functions to events.

on-Properties of HTML tags

The HTML language allows you to define the listener code for some events directly in the attributes of the element tag.

<body onload= "dosomething ()" ><div onclick= "console.log (' triggering event ')" >

  

The above code specifies the listener function for the load event of the body node and the Click event of the div node.

The listener function specified with this method will only be triggered during the bubbling phase.

Note that when you use this method, the value of the on-property is "Listener code", not "listener function." That is, once the specified event occurs, the code is passed in as-is to the JavaScript engine execution. Therefore, if you want to execute a function, you must add a pair of parentheses after the function name.

In addition, the Setattribue method of element node is actually set this effect.

El.setattribute (' onclick ', ' dosomething () ');
Event Properties for ELEMENT nodes

ELEMENT nodes have event properties that can define a listener function.

window.onload = Dosomething;div.onclick = function (event) {  console.log (' triggering event ');};

The listener function specified with this method will only be triggered during the bubbling phase.

AddEventListener method

The AddEventListener method of the element node, document node, window object can also define the listener function for the event.

Window.addeventlistener (' Load ', dosomething, false);

In the above three methods, the first "on-attribute of HTML tag" violates the principle of separating HTML from JavaScript code; The disadvantage of the second "element node's event properties" is that only one listener function can be defined for the same event, i.e., If you define the OnClick property two times, the next definition overwrites the previous one. Therefore, neither of these methods is recommended, except for program compatibility issues, because all browsers support both methods.

AddEventListener is the recommended method for specifying a listener function. It has the following advantages:

  • You can add multiple listener functions for the same event.

  • The ability to specify at which stage (capture stage or bubbling stage) to trigger back the listener function.

  • In addition to DOM nodes, they can also be deployed on objects such as window, XMLHttpRequest, and so on, equal to the listener function interface that unifies the entire JavaScript.

  

The This object points to

In practical programming, the This object inside the listener function often needs to point to the element node that triggered the event.

The AddEventListener method specifies the listener function in which the internal this object always points to the node that triggered the event.

The HTML code is//<p id= "para" >hello</p>var id = ' doc '; var para = document.getElementById (' para '); function Hello ( ) {  console.log (this.id);} Para.addeventlistener (' Click ', Hello, false);

Executing the above code, clicking on the p node will output para. This is because the listener function is "copied" as a property of the node, and can be seen more clearly using the following notation.

Para.onclick = Hello;

If you deploy the listener function above the on-property of the element node, this does not point to the element node that triggered the event.

<p id= "para" onclick= "Hello ()" >Hello</p><!--or using JavaScript code  --><script>  Pelement.setattribute (' onclick ', ' hello () ');</script>

Executing the above code, clicking on the P node will output doc. This is because this is just called the Hello function, and the Hello function is actually executed at the global scope, equivalent to the following code.

Para.onclick = function () {  hello ();}

One workaround is to write the code to be executed directly in the On-property without introducing a function scope. Because the On-property is executed on the current node.

<p id= "para" onclick= "Console.log (ID)" >Hello</p><!--or--><p id= "para" onclick= "Console.log ( this.id) ">Hello</p>

To summarize, the This object, which is written below, points to the element node.

JavaScript code Element.onclick = Printelement.addeventlistener (' Click ', Print, false) Element.onclick = function () { Console.log (this.id);} HTML code <element onclick= "Console.log (this.id)" >

The This object, which is the following notation, points to the global object.

JavaScript code Element.onclick = function () {dosomething ()};element.setattribute (' onclick ', ' dosomething () ');// HTML code <element onclick= "dosomething ()" >

  

Three stages of the spreading

When an event occurs, it propagates between different DOM nodes (propagation). This propagation is divided into three stages:

  • The first stage: conduction from the Window object to the target node, called the capture phase.

  • Second stage: triggered on the target node, called the target phase.

  • Phase three: Conduction back to the window object from the target node, called the "bubbling Phase" (bubbling phase).

This three-stage propagation model causes an event to be triggered on multiple nodes. For example, suppose a div node is nested within a P node.

<div>  <p>click me</p></div>

If you set a listener function on the Click event of these two nodes, the Click event is triggered four times.

var phases = {  1: ' Capture ',  2: ' Target ',  3: ' bubble '};var div = document.queryselector (' div '); var p = documen T.queryselector (' P ');d iv.addeventlistener (' Click ', Callback, True);p. AddEventListener (' Click ', Callback, true); Div.addeventlistener (' Click ', Callback, False);p. AddEventListener (' Click ', Callback, false), function callback (event ) {  var tag = event.currentTarget.tagName;  var phase = Phases[event.eventphase];  Console.log ("tag: '" + Tag + ". Eventphase: ' + phase + ' ');} Click on the result later//TAG: ' DIV '. Eventphase: ' Capture '//Tag: ' P '. Eventphase: ' target '//Tag: ' P '. Eventphase: ' target '//Tag: ' DIV '. Eventphase: ' Bubble '

The above code indicates that the click event was triggered four times: the capture and bubbling stages of the P node are 1 times each, and the capture and bubbling stages of the DIV node are 1 times each.

  1. Capture phase: When an event propagates from a div to P, the click event of the div is triggered;
  2. Target stage: The Click event of P is triggered when the event reaches p from the Div;
  3. Target stage: The Click event of P is triggered when the event leaves P;
  4. Bubbling stage: When the event returns a div from P, the DIV's Click event is triggered again.

When a user clicks on a webpage, the browser always assumes the target node of the Click event, which is the deepest nested node (nested at the p node of the div node).

The topmost object of event propagation is window, followed by document,html (document.documentelement) and Body (document.dody). That is, if there is a DIV element in the BODY element, click the element. The sequence of propagation of events in the capture phase is window, document, HTML, body, Div, in the bubbling phase of Div, body, HTML, document, window.

Agent for Event

Because events propagate up to the parent node in the bubbling phase, the listener functions of the node can be defined on the parent node, and the listener functions of the parent node uniformly handle the events of multiple child elements. This method is called the agent for the event (delegation).

var ul = document.queryselector (' ul '); Ul.addeventlistener (' Click ', Function (event) {  if ( Event.target.tagName.toLowerCase () = = = ' Li ') {    //Some Code  }});

The Listener function for the Click event of the above code is defined on the UL node, but in fact it handles the Click event of the child node li. The advantage of this is that as long as you define a listener function, you can handle the events of multiple child nodes, and then add child nodes later, the listener function is still valid.

You can use the Stoppropagation method of the event object if you want the event to be no longer propagated until it has reached a node.

P.addeventlistener (' click ', Function (event) {  event.stoppropagation ();});

  

With the above code, the click event is no longer propagated upward (the parent node's direction) after it reaches the P node in the bubbling phase.

However, the Stoppropagation method does not block the listener function for other click events on the P node. If you want to stop triggering those listening functions, you can use the Stopimmediatepropagation method.

P.addeventlistener (' click ', Function (event) {event.stopimmediatepropagation ();}); P.addeventlistener (' click ', Function (event) {//will not be triggered});

  

Event Object

After the event occurs, an event object is generated and passed as a parameter to the listener function. The browser native provides an event object, and all events are instances of this object, or inherited Event.prototype objects.

The event object itself is a constructor that can be used to generate a new instance.

event = new Event (Typearg, Eventinit);

The event constructor accepts two parameters. The first argument is a string that represents the name of the event, and the second argument is an object that represents the configuration of the event object. The parameter can have the following two properties.

  • Bubbles: Boolean, optional, default = False to indicate whether the event object is bubbling.

  • Cancelable: boolean, optional, default = False to indicate whether the event can be canceled.

var ev = new Event ("look", {"Bubbles": true, "cancelable": false});d ocument.dispatchevent (EV);

The code above creates a new look event instance and then uses the Dispatchevent method to trigger the event.

IE8 and the following versions, the event object is not passed as a parameter, but is read through the event property of the Window object, and the target property of the event object is called the Srcelement property. Therefore, the previous access to event information is often written as follows.

  

function MyEventHandler (event) {  var actualevent = Event | | window.event;  var actualtarget = Actualevent.target | | actualevent.srcelement;  // ...}

The above code is just to illustrate why the previous program wrote this, and in the new code, such a notation should not be used again.

The properties and methods of the event instance.

The Bubbles property returns a Boolean value that indicates whether the current event will bubble. This property is a read-only property and can only be changed when a new event is created. Unless explicitly declared, events generated by the event constructor are not bubbling by default.

  

function Goinput (e) {  if (!e.bubbles) {    Passiton (e);  } else {    dooutput (e);}  }

The above code calls different functions depending on whether the event is bubbling or not.

The Eventphase property returns an integer value that represents the node where the event is currently located.

var phase = Event.eventphase;
  • 0, the event does not currently occur.
  • 1, the event is currently in the capture phase, which is in the propagation process from the ancestor node to the target node. The process is from the Window object to the document node, and then to the Htmlhtmlelement node until the parent node of the target node.
  • 2, the event reaches the target node, which is the node that the target property points to.
  • 3, the event is in the bubbling phase, which is in the reverse propagation process from the target node to the ancestor node. The procedure is from the parent node to the Window object. This phase can occur only if the Bubbles property is true.

Default behavior for events

The Cancelable property returns a Boolean value that indicates whether the event can be canceled. This property is a read-only property and can only be changed when a new event is created. Unless explicitly declared, events generated by the event constructor are not allowed to be canceled by default.

var bool = event.cancelable;

The Defaultprevented property returns a Boolean value that indicates whether the event has called the Preventdefault method.

if (e.defaultprevented) {  //...}

The target node of the event

  The Currenttarget property returns the node on which the event is currently located, that is, the node that the listening function being executed is bound to. As a comparison, the target property returns the node where the event occurred. If the listener function fires during the capture and bubbling phases, the values returned by the two properties are not the same.

  

function Hide (e) {  Console.log (this = = = E.currenttarget);  True  e.currenttarget.style.visibility = "hidden";} Para.addeventlistener (' Click ', hide, false);

In the above code, click the Para node, and the node will not be visible. In addition, in the listener function, the Currenttarget property is actually equivalent to the This object.

The target property returns the node that triggered the event, the node that originated the event. If the listener function does not fire on that node, it is not the same as the value returned by the Currenttarget property.

function Hide (e) {  Console.log (this = = = E.target);  There may not be true  e.target.style.visibility = "hidden";} HTML code for//<p id= "Para" >hello <em>world</em></p>para.addeventlistener (' Click ', Hide, false );

In the above code, if you click on the EM child node of the Para node, it points to the e.target EM child node, causing the EM child node (i.e. the world part) to be invisible and output false.

In Ie6-ie8, the name of this property is not target, but srcelement, so you can often see the following code.

function Hide (e) {  var target = E.target | | e.srcelement;  target.style.visibility = ' hidden ';}

  

Preventdefault ()

The Preventdefault method cancels the browser's default behavior for the current event, such as clicking the link, the browser jumps to the specified page, or by pressing the SPACEBAR, the page scrolls down a distance. This method takes effect only if the Cancelable property of the event is true, and if False, the method is called without any effect.

This method does not prevent further propagation of events (the Stoppropagation method can be used for this purpose). As long as the event is propagated (capturing, targeting, bubbling), the Preventdefault method is used, and the default method of the event is not executed.

HTML code for//<input type= "checkbox" id= "My-checkbox"/>var cb = document.getElementById (' My-checkbox '); Cb.addeventlistener (  ' click ',  function (e) {E.preventdefault ();},  false);

  

The above code is to click on the Radio box event, set the Listener function, cancel the default behavior. Because the default behavior of the browser is to select the Radio box, this code causes the radio box to be selected.

With this method, you can set the check condition for the text input box. If the user's input does not meet the criteria, the character cannot be entered into the text box.

function CheckName (e) {  if (E.charcode < | | E.charcode > 122) {    e.preventdefault ()}  }

  

When the above function is set to the KeyPress listener function of the text box, only lowercase letters will be entered, otherwise the default event of the input event (written to the text box) will be canceled.

If the Listener function returns a Boolean value of false (that is, return false), the browser does not trigger the default behavior, which has the same effect as the Preventdefault method.

Stoppropagation ()

The Stoppropagation method prevents events from propagating in the DOM, preventing the listener functions that are defined on other nodes from being triggered, but not including the newly defined event listener functions on the current node.

function Stopevent (e) {  e.stoppropagation ();} El.addeventlistener (' Click ', Stopevent, false);

Specifying the above function as a listener function prevents the event from bubbling further to the parent node of the El node.

Stopimmediatepropagation ()

The Stopimmediatepropagation method prevents other listener functions of the same event from being called.

If the same node specifies more than one listener function for the same event, the functions are called sequentially, based on the order in which they were added. As long as one of the listener functions calls the Stopimmediatepropagation method, the other listener functions are no longer executed.

function L1 (e) {  e.stopimmediatepropagation ();} function L2 (e) {  console.log (' Hello World ');} El.addeventlistener (' Click ', L1, false); El.addeventlistener (' Click ', L2, false);

The above code on the El node adds two listener functions, L1 and L2, to the click event. Because L1 calls the Stopimmediatepropagation method, L2 is not called.

JavaScript Advanced Programming---Event object

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.