3 Ways to program JavaScript event handlers

Source: Internet
Author: User

Recently this time because every day to modify the site, for the site to do special effects, so see a lot of JS contact events, they will only use a small part, sometimes used when also more chaotic, now the system of finishing a bit, The first thing you'll share with everyone on the Ma Haixiang blog is the JavaScript event handler in 3 ways:

First, what is a JavaScript event?

Event is the heart of the JavaScript app beating, and the glue that sticks everything together, and the event happens when we interact with the Web page in the browser for some type of interaction.

An event might be a user clicking on something, a mouse passing through a specific element, or pressing some key on the keyboard, something that might happen in a Web browser, such as when a Web page is loaded, or when a user scrolls or changes the window size.

Frankly speaking, an event is a specific interaction moment that occurs in a document or browser!

By using JavaScript, you can listen to the occurrence of a particular event and make certain events occur to respond to these events (the code can be queried by the Ma Haixiang blog, "JS Basics: JavaScript Event Trigger list").

Ii. Flow of events

The event flow describes the order in which the events are accepted in the page, and in the early stages of the browser's development, IE and Netscape between the two big browser vendors, and there was a pit-dad situation in which their interpretation of the event stream appeared in two diametrically opposed definitions. That is what we are familiar with: The event bubbling of IE, Netscape event capture. First, a picture, a brief look at the structure:

1. Event bubbling

Event bubbling The event is initially received by the most specific element (the node with the deepest nesting level in the document) and then propagated up to the least specific node (document). The above diagram shows that when you click on the text section, it is first received by the element in text and then propagated to window, which is the process of executing the 6-7-8-9-10.

2. Event Capture

Event captures are events that are initially received by less specific nodes, and the most specific nodes receive the event at the end. Similarly, in the above model, when you click on the text section, it is first received by the window and then propagated to the text element, that is, the process of executing 1-2-3-4-5.

How does it behave in the code? Behind Ma Haixiang will give the code introduction, Everybody Mo urgent!

Iii. 3 Ways to program JavaScript event handlers

We're going to have to deal with him. There are 3 main ways to understand JavaScript event handlers, according to Ma Haixiang:

1. HTML Event handlers

That is, we add the event handler directly in the HTML code, such as this code:

<input id= "btn1" value= "button" type= "button" onclick= "ShowMsg ();" >
<script>
function ShowMsg () {
Alert ("HTML Add Event Processing");
}
</script>

From the above code, we can see that the event processing is directly nested inside the element, so there is a problem: the HTML code and JS is too strong coupling, if one day I want to change JS in showmsg, then I will not only modify JS, I also need to modify the HTML, One or two changes we can accept, but when your code reaches the level of the line, the changes need to be costly, so this way we are not recommended to use.

2, DOM0 level Event processing program

That is to add event handling for the specified object, see the following code

<input id= "btn2" value= "buttons" type= "button" >
<script>
var btn2= document.getelementbyid ("btn2");
Btn2.onclick=function () {
Alert ("DOM0-Level Add event processing");
}
btn.onclick=null;//If you want to delete the BTN2 click event, set it to null
</script>

From the above code, we can see that, relative to the HTML event handler, DOM0 level event, HTML code and JS code coupling has been greatly reduced. However, the smart programmer is still not satisfied, looking for a more convenient way to handle, the following Ma Haixiang to say the third method of processing.

3, DOM2 level Event processing program

DOM2 is also an event handler for specific objects (see the Ma Haixiang Blog's Basic Tutorial Guide to JavaScript Object properties), but it mainly involves two methods for handling the actions of specifying and deleting event handlers: AddEventListener () and RemoveEventListener ().

They all receive three parameters: the event name to process, the function that acts as the event handler, and a Boolean value (whether to handle the event during the capture phase), see the following code:

<input id= "Btn3" value= "buttons" type= "button" >
<script>
var Btn3=document.getelementbyid ("Btn3");
Btn3.addeventlistener ("click", Showmsg,false);//Here we put the last value to false, that is not processed in the capture phase, generally the bubbling processing in the browser compatibility is better
function ShowMsg () {
Alert ("DOM2-Level Add event handler");
}
Btn3.removeeventlistener ("click", Showmsg,false);//If you want to delete this event, just pass in the same parameters
</script>

As we can see here, the last method is more straightforward and easiest when adding a delete event handler. But Ma Haixiang remind you to note that in the event processing, the incoming parameters must be consistent with the previous parameters, or delete will be invalidated!

Iv. process and differences in event bubbling and event capture

Speaking of which, Ma Haixiang will give you a little bit of code to illustrate the process of event bubbling and event capture, as well as to see the difference between them:

<!doctype html>
<meta charset= "UTF-8" >
<title>Document</title>
<style>
#p {width:400px;height:200px;border:1px solid black;}
#c {width:200px;height:100px;border:1px solid red;}
</style>
<body>
<div id= "P" >
I am www.mahaixiang.cn
<div id= "C" >i like www.mahaixiang.cn</div>
</div>
<script>
var p = document.getElementById (' P ');
var c = document.getElementById (' C ');
C.addeventlistener (' click ', function () {
Alert (' child node capture ')
}, True);
C.addeventlistener (' click ', function () {
Alert (' Sub-node bubbling ')
}, False);
P.addeventlistener (' click ', function () {
Alert (' parent node capture ')
}, True);
P.addeventlistener (' click ', function () {
Alert (' parent node bubbling ')
}, False);
</script>
</body>

Run the above code, click on the child element, we will find that the order of execution is: the parent node capture-child node capture-child node bubbling-the parent node bubbles. As you can see from this example, there are three stages in the DOM2 level event:

1, the event capture phase;

2, in the target stage;

3, event bubbling stage.

The first is the capture, then the target phase (that is, where the event is emitted), and finally the bubble,

Unscientific is, incredibly wood has DOM1 level event processing program, everybody notice, don't make a joke!

Ma Haixiang Blog Add: IE event handlers should also have two methods: attachevent () Add event, detachevent () Delete event, both methods receive the same two parameters: event handler name and event handler function.

Why is there no boolean value here? Because IE8 and earlier versions only support event bubbling, the last parameter is the default equivalent of FALSE to handle! (Browsers that support IE event handlers have Ie,opera)

V. Browser compatibility for event handlers

Since different browsers have their own different support for event handlers, are we not going to be compatible with different browsers every time we use an event handler in development? Here Ma Haixiang encapsulation A compatible method, later in the event processing, the direct call can, see the following section of code:

<!doctype html>
<meta charset= "UTF-8" >
<title>Document</title>
<body>
<input id= "btn" type= "button" value= "Buttons" >
<script>
var eventhandler={
Addhandler:function (Element,type,func) {
if (Element.addeventlistener) {
Element.addeventlistener (Type,func,false);
}else if (element.detachevent) {
Element.attachevent (' on ' +type,func);
}else{
element[' on ' +type]=func;
}
},
Removerhandler:function (Element,type,func) {
if (Element.removeeventlistener) {
Element.removeeventlistener (Type,func,false);
}else if (element.detachevent) {
Element.detachevent (' on ' +type,func);
}else{
element[' on ' +type]=null;
}
}
}
function ShowMsg () {
Alert ("Hello");
}
var Btn=document.getelementbyid ("btn");
Eventhandler.addhandler (BTN, "click", ShowMsg);
Eventhandler.removerhandler (BTN, "click", showmsg);//Remove event handling
</script>
</body>

The above code can handle events normally in IE and other browsers, and you can call this code directly later if you need to use a compatibility operation.

Ma Haixiang Blog Comments:

An event object is an object used to record information about events that occur, but only when an event occurs, and only inside the event handler, the event object is destroyed after all event handlers have run.

This article for Ma Haixiang Blog original article, if want to reprint, please indicate the original site from the http://www.mahaixiang.cn/js/694.html, annotated source, otherwise, no reprint; Thank you!

3 Ways to program JavaScript event handlers

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.