Common Methods for adding and removing functions in javascript

Source: Internet
Author: User

// Method for adding a function
Function addEvent (node, type, listener ){
If (node. addEventListener ){
// W3C method (DOM method)
// The false statement in the following statement is used for the bubble stage. If it is true, it is used for the capture stage (IE does not support capturing). Therefore, false is used for unification.
Node. addEventListener (type, listener, false );
Return true;
} Else if (node. attachEvent ){
// MSIE method (IE method)
Node ['E' + type + listener] = listener;
Node [type + listener] = function (){
Node ['E' + type + listener] (window. event );
};
Node. attachEvent ('on' + type, node [type + listener]);
Return true;
}
// If neither method is available, false is returned.
Return false;
}


// Method for removing a function
Function removeEvent (node, type, listener ){
If (node. addEventListener ){
Node. removeEventListener (type, listener, false );
Return true;
} Else if (node. detachEvent ){
Node. detachEvent ('on' + type, listener );
Return true;
}
// If neither method is available, false is returned.
Return false;
}


// The method for adding a load event is as follows:
1. function addLoadEvent (func ){
Var oldonload = window. onload;
If (typeof window. onload! = "Function "){
Window. onload = func;
} Else {
Window. onload = function (){
Oldonload ();
Func ();
}
}
}
2. // use the above addEvent Method
AddEvent (window, 'load', fn );

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.