SoFunction
Updated on 2025-02-28

Example of compatible writing of JS event addition and removal

This article describes the compatible writing of JS event addition and removal. Share it for your reference, as follows:

var EventUtil = {
  addHandler : function (element , type, handler {
     if ( ){
        (type, handler, false);
      }else if ( ) {
        ("on"+type,handler);
      }else {
         element["on" + type] = handler;
      }
    },
  getEvent : function (event){
      return event ? event : ;
     },
   preventDefault : function(event){
      if(){
         ();
      }else{
          = false;
      }
   },
  removeHandsler : function (element , type , handler){
     if(){
         (type , handler , false);
     }else if(){
         ("on" + type , handler);
     }else{
         element["on" + type] = handler;
     }
    }
   stopPropagation : function(event){
      if(){
         ();
      }else {
           = true;
      }
    },
   getRelatedTarget : function(event){
      if(){
          return ;
      }else if (){
          return ;
      }else if(){
          return ;
      }esle {
          return null;
       }
    },
    getButton : function (event){
       if(("MouseEvents" , "2.0")){
          return ;
       }else{
           switch(){
             case 0:
             case 1:
             case 3:
             case 5:
             case 7:
               return 0;
             case 2:
             case 6:
               return 2;
             case 4:
               return 1;
            }
        }
     }
} ;

Among them, the addHandler and removeHandsler methods first detect whether there is a DOM2-level method in the passed element. If there is a DOM2-level method, use this method: the incoming event type, the event handler function and the third parameter fasle (representing the bubble stage). If there is an IE method, adopt the second solution. Note that the event type must be prefixed with "on". The last possibility is to use the DOM0-level method (in modern browsers, the code here should not be executed). At this time, we use square bracket syntax to specify the attribute name as the event handler, or set the attribute to null.

You can use EventUtil objects like the following:

var btn = ("myBtn");
var handler = function(){
  alert("Clicked");
};
(btn , "click", handler);
//Omit other codes(btn, "click", handler);

For more information about JavaScript, readers who are interested in reading this site's special topic:Summary of JavaScript switching effects and techniques》、《Summary of JavaScript search algorithm skills》、《Summary of JavaScript animation special effects and techniques》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.