Several ways to add event handlers for events in the DOM and Cross-browser

Source: Internet
Author: User

1. The traditional way is to assign a function to an event handler property. Look at the DOM0-level approach for example:

var btn = document.getElementById ("mybtn");
Btn.onclick = function () {
    alert (this.id);//"Mybtn"
}

The event handler specified using the DOM0-level method is considered a method of the element, so this in the program refers to the current element btn, which can access any of the attributes and methods of the element. Event handlers added in this manner are processed during the bubbling phase of the event stream.
You can also delete an event handler: Btn.onclick = null; Deletes an event handler.

2. In the DOM2 level event, two methods are defined to handle actions that specify and delete event handlers: AddEventListener () and RemoveEventListener (). They accept 3 parameters: The event name to be processed, the function as the event handler, and a Boolean value. A Boolean value of TRUE indicates that an event handler is invoked during the capture phase, or false, that the event handler is invoked during the bubbling phase. As with the DOM0 level, this refers to the current element.
The main benefit is that you can add multiple event handlers, such as:

var btn = document.getElementById ("mybtn");
Btn.addeventlistener ("click", Function () {
    alert (this.id);
}, False);
Btn.addeventlistener ("click", Function () {
    alert ("Me");
}, False);

Will be triggered in the order added, first display ID, then show me
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 used to add handlers. This means that anonymous functions added through AddEventListener () will not be removed, as in the following example:

var btn = document.getElementById ("mybtn");
Btn.addeventlistener ("click", Function () {
    alert (this.id);
}, False);
Btn.removeeventlistener ("click", Function () { 
    alert (this.id);,
false);//no use, because this anonymous function and the above anonymous function do not use a function.

To remove an anonymous function, you can place the event handler in a variable such as:

var btn = document.getElementById ("mybtn");
var handler = function () {
    alert (this.id);
};
Btn.addeventlistener ("Click", Handler, false);
Btn.removeeventlistener ("Click", Handler, false); Effective

In most cases, to maximize compatibility with various browsers, event handlers are added to the bubbling phase of the event stream, and event handlers are added to the capture phase when specifically needed to intercept in the capture phase, and event handlers are not recommended to be added during the capture phase, if not specifically required.

The 3.IE event handler also has two own methods: Attachevent () and DetachEvent (). Accept two parameters: event name and event handler function. Are added to the bubbling phase.
Unlike the DOM0 level, the event handler is run in the global scope, this equals window. Example:

var btn = document.getElementById ("mybtn");
Btn.attachevent ("onclick", function () {
    alert (this = = window);//true
});//The event name for the first argument is "onclick" not click

Similar to AddEventListener, you can add multiple events:

var btn = document.getElementById ("mybtn");
Btn.attachevent ("onclick", function () {
    alert (this.id)
 });
Btn.addeventlistener ("click", Function () {
    alert ("Me");
});

To remove an event handler, it is the same as AddEventListener ():

var btn = document.getElementById ("mybtn");
var handler = function () {
    alert ("clicked");
Btn.attachevent ("onclick", handler);
Btn.detachevent ("onclick", handler); Effective

4. Cross-browser event handlers
Create a Method addhandler (), which is responsible for integrating DOM0, DOM2, and IE methods to add events, RemoveHandler () Similarly, AddHandler accepts 3 parameters: the element to be manipulated, the event name, and the event handler function. Encapsulated in a Eventutility object:

var eventutil = {addhandler:function (element, type, handler) {//To determine if there is a DOM2-level method
        if (Element.addeventlistener) {Element.addeventlistener (type, handler, false);
        //Determine if IE version else if (element.attachevent) {element.attachevent ("on" + type, handler); }//To determine if there is a DOM0-level method else {element[' on ' + type] = handler}}, RemoveHandle R:function (element, type, handler) {if (Element.removeeventlistener) {Element.removeeventlistener (Ty
        PE, handler, false);
        else if (element.detachevent) {element.detachevent ("on" + type, handler);
        else {element["on" + type] = NULL;

}
    }
};
This can be done using var btn = document.getElementById ("mybtn");
var handler = function () {alert ("clicked");}
Eventutil.addhandler (BTN, "click", Handler); Eventutil.removehandler (BTN, "click", handler); 

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.