Add events to JavaScript DOM

Source: Internet
Author: User

For browsers that support DOM, The addEventListener () method is used to add events to objects!
For MSIE, attachEvent () is used to add events to the object! This makes it necessary to use a container to load the event handling methods on these two different browsers! In this way, we can directly call the addEvent () method to add events to the object!
Isn't it more convenient ?! Haha ......
Let's take a look!
/**
* Register a listening event to an element
* @ Param {Object} the Object of the event to be added to node
* @ Param {Object} type event type
* @ Param {Object} listener event Method
*/
Function addEvent (node, type, listener ){
// Use the previous method to check compatibility to ensure smooth degradation
If (! (Node = $ (node) return false;

If (node. attachEvent) {// This is the method for IE
Node ['E' + type + listener] = listener;
Node [type + listener] = function () {node ['E' + type + listener] (window. event );}
Node. attachEvent ('on' + type, node [type + listener]);
Return true;
} Else if (node. addEventListener ){
// This method is applicable to browsers that support DOM.
Node. addEventListener (type, listener, false );
Return true;
}
// If neither method is available, false is returned;
Return false;
};
Window ['liujingning'] ['addevent'] = addEvent;

Usage:
For example, if we want to add an event to the onload () of the page, we can write as follows:
Liujingning. addEvent (window, 'load', function (Event) {// write the code you want to write here}
We can also add events to an ID.
Var getId = document. getElementById ('A ');
Liujingning. addEvent (getId, 'load', function (Event) {// write the code you want to write here}

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.