The most detailed explanations of JavaScript and events

Source: Internet
Author: User
Tags event listener tag name

When interacting with the browser, the browser triggers various events. For example, when we open a webpage, the browser loads the page, it triggers an load event, and when we click on a "place" in the page, the browser triggers an event in that "place" click .

In this way, we can write JavaScript to implement some function extensions by listening to an event. For example, listening to load events and displaying welcome messages, the welcome message is displayed when a Web page is loaded by the browser.

Here's an introduction to the event.

Base Event Operation Listener Event

The browser triggers the event according to certain actions, and if we need to handle an event, we need to listen to the event. There are several main ways to listen to events:

HTML Inline properties (avoid use)

HTML elements directly fill in the event about the property, the property value is the JavaScript code, you can trigger the event, the execution of the property value of the content.

For example:

<button onclick= "alert (' You clicked this button ');" > Click this button </button>

onclickProperty represents the trigger click , and the contents of the property value (JavaScript code) are executed when the HTML node is clicked.

Obviously, using this approach, the JavaScript code is coupled with the HTML code, which is inconvenient for maintenance and development. So try to avoid using this method unless you have to use it, such as statistical link click Data.

DOM Property Binding

You can also set the DOM property directly to specify the handler for an event, which is relatively straightforward:

Element.onclick = function (event) {    alert (' You clicked this button ');};

The above code is element the event that listens for nodes click . It is relatively easy to understand, and has good compatibility. But there is also a flaw, because the direct assignment to the corresponding property, if you in the following code again to element bind a callback function, will overwrite the contents of the previous callback function.

Although there are several ways to implement multiple bindings, the following standard event listener functions are recommended.

Using Event listener functions

The standard event listener functions are as follows:

Element.addeventlistener (<EVENT-NAME>, <callback>, <use-capture>);

Indicates that element an event listener is added to this object, and <event-name> the callback function is called when the Monitor hears an event <callback> . As <use-capture> for this parameter, this indicates whether the event listener listens (set to True) or listens (set to false) in the "bubble" phase during the "capture" phase. For capture and bubbling, we'll explain below.

Use the standard event listener function to rewrite the above example:

var btn = document.getelementsbytagname (' button '), Btn[0].addeventlistener (' click ', Function () {    alert (' You clicked this button ');}, False);

It is best to define an ID or class attribute for the HTML structure, which is easy to select and use as a demo.

Demo:

Remove Event Listener

When we bind an event to an element, the event binding callback function is executed each time the event is triggered. If we want to unbind, we need to use the removeEventListener method:

Element.removeeventlistener (<EVENT-NAME>, <callback>, <use-capture>);

It is important to note that the callback function when binding an event cannot be an anonymous function, it must be a declared function, because a reference to the callback function needs to be passed when the event is unbound to break the binding. For example:

var fun = function () {    //function Logic};element.addeventlistener (' Click ', fun, false); Element.removeeventlistener (' Click ', fun, false);

Demo:

Event triggering process

There's a general understanding of what the event is, how to listen and do something, but we don't know enough about the event to trigger the whole process.

Is the triggering process of the event, borrowed the picture of the

Capturing phase (capture Phase)

When we have some action on one of the DOM tree nodes (for example, click, mouse Move Up), there will be an event to launch the past. This event is emitted from the Window and continues through the subordinate nodes until the target node. The process before reaching the target node is the capturing phase (capture Phase).

All the passing nodes trigger this event. The task of the capture phase is to set up this event delivery route so that the bubbling phase follows this route back to Window.

Listening to an event triggered during the capture phase requires the third parameter to be passed in the event listener function true .

Element.addeventlistener (<EVENT-NAME>, <callback>, true);

However, we often pass false when used in general, and we will explain why later.

Goal phase (target Phase)

When the event runs and runs, it runs to the event trigger target node and eventually triggers the event on the target node, which is the target phase.

When you need to be aware, the event-triggered target is always the lowest node. For example, if you click on a piece of text, you think your event target node is div on, but it actually triggers on <p> , and <span> so on, the child nodes. For example:

In the Demo, I listen for the Click event to eject the target node's tag name. When you click the bold font, the target node for the event is the bottommost <strong> node.

Bubbling stage (bubbling Phase)

When the event reaches the target node, it is returned along the original path, as this process resembles blisters floating from the bottom to the top, so called the bubbling phase.

In actual use, you do not need to accurately bind the event listener function to the lowest node can also work properly. For example, in the example above, you want to <div> bind a callback function for this order, you do not <div> have to tie all the sub-nodes below all the order-click events, only need to be <div> bound for this one node. Because the click event of its child node occurs, it will bubble up and occur on top of it <div> .

For these three stages, Wilsonpage has done a great Demo and can look at:

Why not use a third parameter true

Let's take a look at the above three event triggering stages.

All articles that describe the event will say that addEventListener when you use a function to listen to an event, the third parameter is set false so that when you listen to an event, only the events that occur during the bubbling phase are monitored.

This is because IE browser does not support the interception of events during the capture phase, set for unification, after all, ie browser share is not negligible.

There are some other differences between the Internet Explorer and the standard in the event, which we will focus on later.

Using the event agent (Delegate) to improve performance

Because the event has a bubbling mechanism, all child node events will run back along the parent node, so we can listen to the parent node to implement the function of listening to the child node, which is the event proxy.

There are two main advantages to using event proxies:

    1. Reduce event binding and improve performance. You need to bind a bunch of child nodes before, and now you just need to bind a parent node. Reduces the number of bound event listener functions.
    2. The dynamically changing DOM structure can still be monitored. When a DOM is created dynamically, there is no event listener, unless you re-execute the event listener function and use event snooping without worrying about the issue.

See an example:

In the above example, for simplicity, I use jQuery to implement common event bindings and event proxies. My goal is to listen a to all linked click events, which .ul1 are regular event binding methods, and jQuery loops through each .ul > a structure and binds the event listener function. .ul2is the event listener method, JQuery only for .ul2 structure-bound event listener function, because .ul2 there may be a lot of unrelated nodes will also trigger the click event, so I on passed the second parameter in the function, that is, only listen to a the child node events.

They all work, but when I create a new DOM structure on the fly, the first problem arises, and the ul newly created structure is still .ul1 > a , but there is no binding event, so the callback function cannot be executed. And the second one ul works well, because clicking on the newly created DOM, its events will bubble to the parent node for processing.

If you implement the event proxy in a native way, you need to be aware of filtering non-target nodes, either by ID, class, or tagname, etc., such as:

Element.addeventlistener (' click ', Function (event) {    //) to determine if a node is    (event.target.tagName = = ' a ') {        //A (Some interactive operation    }}, False);
Stop event bubbling (stoppropagation)

All things will have opposites, and the bubbling stage of events, while seemingly good, will have unsuitable venues. More complex applications, because event monitoring is more complex, you may want to listen only to events that occur on specific nodes. This is the time to stop the event bubbling.

Stopping event bubbling requires the use of the event object's stopPropagation method, as follows:

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

In the event listener callback function, a parameter is passed, which is the Event object that invokes the method on the object to stopPropagation stop the event bubbling. An example of an application that bubbles up a stop event:

JS Bin

In the example above, there is a pop-up layer where we can do any action on the popup layer, for example click . When we want to turn off this pop-up layer, click on any structure outside the pop-up layer to turn it off. It first document monitors the nodes for events, click all of which click can be hidden by the popup layer. Similarly, the click action above the popup layer will also cause the popup layer to be hidden. We then bubbled up the popup layer with a stop event and snapped the bubbling route returned by the Click event so that the document action on the popup layer would not be document heard by the event handler.

More about Event The object, we'll cover it below.

Event object for events

When an event is triggered, an event object is created, which contains some useful properties or methods. The event object is passed to our destroy function as the first argument. We can use the following code to print out this event object in the browser:

<button> print Event object</button><script>    var btn = document.getelementsbytagname (' button ');    Btn[0].addeventlistener (' click ', Function (event) {        Console.log (event);    }, False);</script>

You will see a list of properties:

The event object includes a lot of useful information, such as the coordinates of the mouse on the screen when the event is triggered, the DOM details that are triggered, and the stop-bubbling Method (Stoppropagation) inherited from the bottom. Here are some of the more commonly used properties and methods:

type(string)

The name of the event, such as "click".

target(node)

The target node to trigger for the event.

bubbles(Boolean)

Indicates whether the event was triggered during the bubbling phase.

preventDefault(function)

This method disables all default behavior, such as clicking on a a label, opening a new page, and a click not opening a new page if the method is called simultaneously for the tag listener event.

stopPropagation(function)

Stop bubbling, mentioned above, no longer repeat.

stopImmediatePropagation(function)

stopPropagationSimilarly, it prevents other listener functions from being triggered. But unlike stopPropagation the other, it is more "powerful", preventing events from triggering other than the target, or even blocking the same event for the same target node, demo:http://jsfiddle.net/yujiangshui/ju2ujmzp/2/.

cancelable(Boolean)

This property indicates whether the event can disable the event.preventDefault default behavior by calling the method.

eventPhase(number)

The number of this property indicates at what stage the current event is triggered. none:0; capture: 1; target: 2; bubble: 3.

pageXAnd pageY(number)

These two properties represent the coordinates of the mouse relative to the page when the event is triggered. demo:http://api.jquery.com/event.pagex/.

isTrusted(Boolean)

Indicates whether the event was triggered by the browser (user real action) or by JavaScript code.

Events in JQuery

If you are writing an article or Demo, for the sake of simplicity, you can of course use the above event listener functions, as well as the methods provided by the event object. In practice, however, there are some methods and properties that have compatibility issues, so we use jQuery to eliminate compatibility issues.

Here's a simple example of the underlying operation of the event in JQuery.

Binding events and Event proxies

In JQuery, a click() syntactic sugar such as this is provided to bind the corresponding event, but it is recommended that uniform use be used on() to bind the event. Grammar:

. On (events [, selector] [, data], handler)

eventsThat is, the name of the event, you can pass the second parameter to implement the event proxy, the specific document. On () do not repeat here.

Event object for which compatibility has been processed

Event objects Some methods, etc., also have compatibility differences, and jQuery encapsulates them and provides a name that is always named after the standard.

If you want to access the original event object in the JQuery event callback function, you need to use event.originalEvent it to point to the native event object.

Triggering events triggerMethod

Clicking on a click node that is bound to an event naturally triggers the node's click events to execute the corresponding callback function.

triggerMethod can simulate a triggering event, we click another node ELEMENTB, which can be used:

$ (ELEMENTB). On (' click ', Function () {    $ (Elementa). Trigger ("click");});

To trigger the Elementa node's click-Listen callback function. See the documentation for details. Trigger ().

Event Advanced topics IE browser differences and compatibility issues

IE Browser is maverick, it has some differences in the operation and standard of the event. But the Internet Explorer is now starting to reinvent itself, making the browser more standard.

Bind event under IE

An event listener is bound under IE, and in ie9-it is not possible to use standard addEventListener functions, but to use your own attachEvent , specific usage:

Element.attachevent (<EVENT-NAME>, <callback>);

The <event-name> parameters need to be noted, it needs to add a prefix to the event name on , such as an event called click , the standard event listener function listening click , IE here need to listen onclick .

Another, it does not have a third parameter, which means it only supports listening for events triggered during the bubbling phase, so for unification, the third parameter passes false when using the standard event listener function.

Of course, this method in IE9 has been abandoned, in IE11 has been removed, IE is slowly getting better.

What to note in IE for Event objects

There are some differences between the event objects passed in the back function in IE and the standard, which you need window.event to use to get the event object. So you usually write the following code to get the event object:

Event = Event | | Window.event

In addition, there are some event attributes are different, such as the more commonly used event.target properties, IE is not, but instead of using event.srcElement . If your callback function needs to handle the node that triggered the event, then you need to write:

node = event.srcelement | | Event.target;

This is the common point, not much more in detail. In the concept of learning, we do not need to pay for the non-standard cost of learning, in practical applications, the class library has helped us encapsulate these compatibility issues. It is gratifying that IE browser is now also beginning to continue to the standard progress.

Scope problem of event callback function

There is a problem with the scope of the callback function that is bound to the event, let's look at an example:

Events in javascript:removing event listeners

The function scope of the callback function call user.greeting should be user under, and this expected output is My name is Bob output My name is undefined . This is because the function executes with the current element as the scope of the event binding function. To prove this, we can add properties for the current element :

Element.firstname = ' Jiangshui ';

Click again to eject correctly My name is jiangshui . So let's solve this problem.

Using anonymous functions

We wrap a layer of anonymous functions for the callback function.

Events in javascript:removing event listeners

After the package, although the scope of the anonymous function is directed to the event-triggering element, the execution of the content is like a direct call without affecting its scope.

Using the Bind method

The use of anonymous functions is flawed, each call is wrapped into an anonymous function, add redundant code, etc., in addition, if you want to use removeEventListener unbind, you need to create a function reference. A Function type provides a bind method that can be scoped to a function, regardless of where the function is called, and does not change its scope. The scope is bound by the following statement:

user.greeting = user.greeting.bind (user);

So we can use it directly:

Element.addeventlistener (' click ', user.greeting);
Common Events and tips

There are many kinds of actions for users, so there are many events. For ease of development, the browser provides a number of events, so there are a lot of events. Here are just a few common events and tips to use.

load

loadThe event is triggered when the resource load is complete. This resource can be a picture, CSS file, JS file, video, document, window, and so on.

The most common is to listen to the event of the window load , when all the resources in the page after all the load is completed, will be triggered. For example, with JS on pictures and other resources processing, we trigger in the load event, you can ensure that JS will not start processing resources when the resource is not loaded to cause error.

Similarly, you can listen to other resources such as pictures and other load situations.

beforeunload

When the browser enters some content in the input box on the page, it may cause the input information to be lost if the page is not saved and the wrong operation is turned off.

When the user enters the information but does not save the page, we can start to listen to this event, for example:

Window.addeventlistener ("Beforeunload", function (event) {    Event.returnvalue = "Discard the current unsaved content and close the page?" ";});

When trying to close the page, the window will block the operation, click on the confirmation will not be closed. Of course, if not necessary, do not listen, do not think that using it can keep the browser for you.

resize

This event is triggered when the node size is changed. Typically used on Windows to listen for changes in the browser window. Often used in complex layouts and responses.

Common parallax scrolling effects sites and similar complex layout sites often use JavaScript to calculate size and location. If the user resizes the browser, the size and position do not change as the changes occur. Listen for the event on the window, and invoke a function that calculates the size and position when triggered, and can be recalculated based on the size of the browser.

However, it is important to note that when any change in the browser will trigger the resize event, even if the browser width is reduced by 1px, so the browser will trigger a large number of resize events, your callback function will be a lot of execution, resulting in card, crash and so on.

You can use the function throttle or debounce techniques to optimize, throttle method is the general idea is that in a certain period of time, no matter how many calls, only one function, the time of arrival execution; debounce The general idea of the method is to wait for a certain period of time to repeat the call, if it is not called again, execute the function, if there are repeated calls, do not continue to wait. For more detailed information about them, I'll introduce them later on in my blog, which I will not repeat here.

error

Events are triggered when we fail to load a resource or load successfully but only partially, and error we can listen to the event to prompt a friendly error or other processing. For example, JS resource failed to load, then prompted to try to refresh, picture resource loading failed, under the picture prompts the picture loading failure, etc. The event does not bubble. Because the child node failed to load, it does not mean that the parent node failed to load, so your handler must be exactly bound to the target node.

It is important to note that for this event, you can use addEventListener and so on to listen, but sometimes the failure condition (see this example), this is because the error event has been triggered, your JS listening processing code has not been loaded in execution. In order to avoid this situation, it is better to use the inline method:

If there are other common events, please add a message.

Triggering built-in events with JavaScript impersonation

Built-in events can also be triggered by JavaScript simulations, such as the following function that simulates triggering a click event:

function Simulateclick () {  var event = new MouseEvent (' click ', {    ' View ': window,    ' Bubbles ': true,    ' Cancelable ': True  });  var cb = document.getElementById (' checkbox ');   var canceled =!cb.dispatchevent (event);  if (canceled) {    //A handler called Preventdefault.    Alert ("Canceled");  } else {    //None of the handlers called Preventdefault.    Alert ("Not Canceled");}  }

You can read this Demo to learn more.

Custom events

We can customize events to achieve more flexible development, events are used well can be a very powerful tool, event-based development has many advantages (described later).

Functions with custom events have Event , CustomEvent and dispatchEvent .

To customize the event directly, use the Event constructor:

var event = new Event (' Build ');//Listen for the Event.elem.addEventListener (' Build ', function (e) {...}, false);//Disp Atch the Event.elem.dispatchEvent (event);

CustomEventYou can create a more highly customized event, and you can include some data with the following:

var myevent = new Customevent (eventname, Options);

Where options can be:

{    detail: {        ...    },    bubbles:true,    Cancelable:false}

detailIt can hold some initialization information and can be called at the time of triggering. Other properties are functions that define whether the event has bubbling, and so on.

Built-in events are triggered by the browser based on certain actions, and custom events need to be triggered manually. dispatchEventa function is used to trigger an event:

Element.dispatchevent (customevent);

The above code indicates that the Customevent event is triggered on element above. In combination, it is:

Add an appropriate event Listenerobj.addeventlistener ("Cat", Function (e) {process (E.detail)});//Create and dispatch The Eventvar event = new Customevent ("cat", {"detail": {"Hazcheeseburger": True}}); Obj.dispatchevent (event);

Using custom events requires attention to compatibility issues, and using jQuery is a lot easier:

Bind custom Event $ (Element). On (' Mycustomevent ', function () {});//Trigger Event $ (element). Trigger (' mycustomevent ');

In addition, you can pass more parameter information when a custom event is triggered:

$ ("P"). On ("Mycustomevent", Function (event, MyName) {  $ (this). Text (MyName + ", Hi there!");}); $ ("button"). Click (function () {  $ ("P"). Trigger ("Mycustomevent", ["John"]);});

For more detailed usage please see Introducing Custom Events, which is not mentioned here.

Applying events in development

When we manipulate a DOM and issue an event, we can write code in another place to capture the event execution processing logic. The triggering action and the capture processing operation are separate. We can decouple the program according to this feature.

Decoupling with events

We can divide an entire function into separate small functions, each of which binds an event, and a "controller" is responsible for triggering an event based on the condition. In this way, triggering the event outside can also invoke the corresponding function to make it more flexible.

In the "MVC-based JavaScript Web Rich application Development" book, there are more specific examples, interested friends can buy a look.

Publish (Publish) and subscribe (Subscribe) modes

For the above usage, continue to abstract, that is, publish and subscribe to the development model. As its name says, this pattern has two roles: Publisher and subscriber, in addition there is a channel where the publisher is triggered to send letters to the channel, the Subscriber receives the message from the channel, and executes a corresponding logic if a particular letter is received. This way, the publisher and the Subscriber are completely decoupled, with only one channel connected. This makes it very easy to scale, and does not introduce additional dependencies.

This way, if you need to add a new feature, you only need to add a new subscriber (and its execution logic) to listen for a new type of letter in the channel. You can then send a new type of letter to the app through the publisher.

Specifically, it is recommended that Cowboy developed Tiny Pub Sub, implemented by jquery, is very simple and intuitive, and jquery is great. The code is just a few lines:

(function ($) {  var o = $ ({});  $.subscribe = function () {    o.on.apply (o, arguments);  };  $.unsubscribe = function () {    o.off.apply (o, arguments);  };  $.publish = function () {    o.trigger.apply (o, arguments);  };} (JQuery));

Defines an object as a channel, then provides three methods, subscribers, unsubscribe, publisher.

Summarize and expand reading

The basics of event-related basics are these, and more remains to be explored. This document references and recommended extensions are read as follows (thanks to them):

    • Dom-level-3-events
    • Event on MDN
    • Events of JQuery
    • Introducing Custom Events
    • An Introduction to DOM Events
    • "MVC-based JavaScript Web rich application Development"

The most detailed explanations of JavaScript and 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.