JS(9) Event Handling

Keywords: IE Javascript Attribute Firefox

I. HTML Event Processing

1. Advantages:

  • Specifying event handling in HTML creates a function that encapsulates the value of element attributes. This function has a local variable event, that is, event object, through which event object can be accessed directly.
  • You can use with to extend the scope to allow time handlers to access other form fields without reference.

2. Disadvantages:

  • There is a time lag problem.
  • The scope chain of event handlers has different results in different browsers.
  • HTML and JavaScript code are tightly coupled. To replace event handlers, two changes are needed: HTML code and JavaScript code.

Through analysis, we try to specify event handlers with JavaScript in complex programs.

2. DOM0 Event Handler

1. The traditional way to specify event handlers through JavaScript is to assign a function to an event handler property. The advantages of traditional methods are: first, it is simple; second, it has the advantage of cross-browser. To specify an event handler using JavaScript, you must first obtain an object reference to operate on.

2. Each element has its own event handler properties, which are usually all lowercase. Setting the attribute value to a function specifies the event handler.

The DOM0 level event handler is considered to be the method of the element, which runs in the scope of the element. This in the function refers to the current element, and this can access all the attributes and methods of the element.

3. Delete DOM0 event handler: btn.onclick = null;

3. DOM2 Event Handler

1. Two methods are defined to handle the operation of formulating and deleting event handlers: addEventListener() and removeEventListener(), which are supported by all DOM nodes.

They all accept three function parameters: the name of the event to be processed, the function of the seat event handler, and a Boolean value. If the Boolean value is true, it means that the event handler is invoked in the capture phase; if false, it means that the event handler is invoked in the bubble phase.

2. Multiple event handlers can be added using DOM2 level method, and the execution order of multiple events can be triggered in the order of adding them.

3. AddiEventListener () can only be removed by removeEventListener(), which means that the anonymous function added by addEventListener() cannot be removed.

4. In most cases, event handlers are added to the bubble phase of events to maximize compatibility with browsers (meaning that the third Boolean value is filled in as false as possible).

IE9, Firefox, Safari, Chrome and Opera support DOM2 level event handlers.

IV. IE Event Processing Procedure

1. attachEvent() and detachEvent() receive the same two parameters: the event handler name and the event handler function. The event name is "click" in DOM2 and "onclick" in IE.

2. The difference between attachEvent() and DOM0 in IE is that the scope of event processing is different. In the DOM0 method, the event handler runs in the scope of the element to which it belongs; in the case of attachEvent() method, the event handler runs in the global scope, so this is equal to window.

3. When adding multiple methods, the execution order is in the reverse order of definition.

4. Remove the event handler: detachEvent(), so long as the reference to the same function can be passed to detachEvent(), the corresponding event handler can be removed.

var btn = document.getElementById("myBtn");
var handler = function(){
   alert("clicked");
}
btn.attachEvent("onclick",handler);
btn.detachEvent("onclick",handler);
Only IE and Opera support IE event handlers.

5. Cross-browser Event Handler

A cross-browser event processing object adapted from Zakas

var EventUtil={
	
   addHandler:function(element,type,handler){ //Adding Events
      if(element.addEventListener){ 
         element.addEventListener(type,handler,false);  //Adding events using DOM2-level methods
      }else if(element.attachEvent){                    //Adding Events Using IE Method
         element.attachEvent("on"+type,handler);
      }else{
         element["on"+type]=handler;          //Adding events using DOM0-level methods
      }
   },  

   removeHandler:function(element,type,handler){  //Cancel event
      if(element.removeEventListener){
         element.removeEventListener(type,handler,false);
      }else if(element.detachEvent){
         element.detachEvent("on"+type,handler);
      }else{
         element["on"+type]=null;
      }
   },

   getEvent:function(event){  //Use this method to get event objects across browsers
      return event?event:window.event;
   },
	
   getTarget:function(event){  //Returns the actual target of the event
      return event.target||event.srcElement;
   },
	
   preventDefault:function(event){   //Prevent default behavior of events
      if(event.preventDefault){
         event.preventDefault(); 
      }else{
         event.returnValue=false;
      }
   },

   stopPropagation:function(event){  //Stop the propagation of events in DOM immediately
                                     //Avoid triggering event handlers registered on document.body
      if(event.stopPropagation){
         event.stopPropagation();
      }else{
         event.cancelBubble=true;
      }
   },
		
   getRelatedTarget:function(event){  //Get mouseover and mouseout related elements
      if(event.relatedTarget){
         return event.relatedTarget;
      }else if(event.toElement){      //Compatible with IE8-
         return event.toElement;
      }else if(event.formElement){
         return event.formElement;
      }else{
         return null;
      }
   },
		
   getButton:function(event){    //Which button in the mouse is the button that gets mousedown or mouseup pressed or released?
      if(document.implementation.hasFeature("MouseEvents","2.0")){
         return event.button;
      }else{
         switch(event.button){   //Mapping button attributes in IE model to button attributes in DOM model
            case 0:
            case 1:
            case 3:
            case 5:
            case 7:
               return 0;  //Press the main mouse button (usually the left button)
            case 2:
            case 6:
               return 2;  //Press the middle mouse button
            case 4:
               return 1;  //Mouse sub-button (usually right-click)
         }
      }
   },
		
   getWheelDelta:function(event){ //Gets the numeric value representing the rolling direction of the mouse wheel
      if(event.wheelDelta){
         return event.wheelDelta;
      }else{
         return -event.detail*40;
      }
   },
		
   getCharCode:function(event){   //To get the same character encoding across browsers, you need to use it in keypress events
      if(typeof event.charCode=="number"){
         return event.charCode;
      }else{
         return event.keyCode;
      }
   }
		
};

Posted by haroon on Fri, 28 Jun 2019 11:15:16 -0700