SoFunction
Updated on 2025-04-05

Understanding events in JavaScript

In learning many languages, "events" are a relatively difficult concept to understand, but it is also a very important concept. The same is true for event processing in javascript. It is precisely because of event processing that the Ajax drag effect occurs. This article discusses event processing in JavaScript. After reading it, you will know that many Ajax frameworks implement the principle of dragging effects.
1. IE Event object
(I) Main properties and methods of IE Event objects
There is an object event in IE that is specifically responsible for event processing. This object is responsible for handling events and contains many attributes and methods. Through the call of these methods and attributes, many event processing can be completed.
type: The type of event is a string without the "on" prefix in the HTML tag attribute. For example, "Click" represents the click event.
srcElement: The event source is the element where the event occurs.
button: Declares the mouse button being pressed, which is an integer. 1 represents the left mouse button, 2 represents the right mouse button, and 4 represents the middle key of the mouse. If multiple mouse buttons are pressed, these values ​​are added together, so 3 represents the left and right keys are pressed at the same time.
clientX/clientY: refers to the horizontal and vertical coordinates of the mouse when an event occurs. The returned integers are integers, and their values ​​are generated relative to the upper left corner of the consumable window.
offsetX/offsetY: The position of the mouse pointer relative to the source element, which pixel of the Image object is clicked.
altKey, ctrlKey, shiftKey: As the name suggests, these properties refer to whether the Alt, Ctrl or Shift keys are pressed and held down at the same time when a mouse event occurs. The return is a Boolean value.
keyCode: Returns the key code and the Unicode characters of the keypress event when the keydown and keyup events occur.
fromElement and toElement are the document elements moved by the mouseover event, and the latter refers to the document elements moved by the mouseout event.
cancelBubble: A boolean property that when set to true, stops the event further bubbles to the inclusion level elements.
returnValue: A Boolean property. When set to false, the browser can be organized to perform the default event actions, which is equivalent to <a href="#" onclick="ProcessMethod();return false;"  />.
attachEvent() and detachEvent() methods: To formulate a method for registering multiple event handling functions for the DOM object event type, they have two parameters, the first is the event type and the second is the event handling function. When the attachEvent() event is executed, this keyword points to the window object, not the element where the event occurs.
(II) Some explanations of IE Event objects
The Event object is a global property
In IE, the Event object cannot be passed as a parameter to the event handler, and the Event object can only be referenced using or event. Because in IE, Event is a property of window, that is, event is a global variable, which provides details of the event.
Bubble of events in IE: Events in IE can bubble to the upper layer little by little along the inclusion level. That is to say, the event processing function defined by the lower DOM node. If there is an event processing function of the same event type as the lower layer at the upper layer, the event processing function of the upper layer will also be executed. For example, the <div> tag contains <a>. If both tags have onclick event processing functions, then the execution situation is to first execute the onclick event processing function of the <a> tag, and then execute the <div> event processing function. If you want the event handling function of <a> to be executed after the event handling function of <a> is executed and the event handling function of the upper layer <div> is not intended to be executed, then set cancelBubble to false.

2. Examples of dragging DOM elements in IE
Copy the codeThe code is as follows:

/*
This function is called by mousedown event processing
It registers a temporary capture event handler for subsequent mousemove and mouseup events
And use these event handlers to drag the specified document element
The second parameter must be the event object of the mousedown event
*/
function beginDrag(elementToDrag,event)
{
//Where is the current location of this element
//The style properties of this element must have left and top CSS properties
//In addition, we assume that they use pixels as units
  //var x=parseInt();
  //var y=parseInt();

// Calculate the distance between a point and a mouse click. The nested moveHandler function below requires these values
  var deltaX=-parseInt();
  var deltaY=-parseInt();

//   The handler of mousemove and mouseup events that occur after registering the mousedown event
//   Note that they are registered as capture event handlers for documents
//   These event handlers remain active while the mouse button remains pressed
//    When the buttons are released, they are deleted
  ("onmousemove",moveHandler);
  ("onmouseup",upHandler);

//We have processed the event, don't let other elements see it
 =true;
 =false;

  /*
This is the handler that catches the mousemove event when the element is dragged, which responds to the moving element.

  */
  function moveHandler(e) 
  {
//Move the element to the current mouse position
    e=;
    =(-deltaX)+"px";
    =(-deltaY)+"px";

//Don't let other elements see the event
    =true;   
  }

  /*
This event will capture the mouseup event that occurs when the drag is over
  */
  function upHandler(e)
  {
//Log out event handler
      ("onmouseup",upHandler);
      ("onmousemove",moveHandler);}

      =true;
    } 
HTML file code that calls it:
 <html>
 <head>
     <title>Untitled Page</title>
     <script type="text/javascript" src=""></script>
 </head>
 <body>
 <div style="position:absolute;left:100px;top:100px;background-color:White;border:solid black;">
   <div style="background-color:Gray;border-bottom:solid black;padding:3px;font-family:Sans-Serif;font-weight:bold;" onmousedown="beginDrag(,event);">
Drag me&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
   </div>
   <div>
   <p>This is a ,testing</p></div>
 </div>
 </body>

3. Advanced event processing in DOM
Event processing in IE 6 is not the event processing model of the W3C DOM standard. Therefore, if the above code is run in the Mozilla Firefox browser, it will lose its effect. At the same time, the upcoming IE 7 will also support the W3C DOM secondary standard, so it is important to master the advanced event processing of DOM, because the W3C DOM secondary standard is the future development direction of the web. At the same time, the W3C DOM API is very commonly used, providing a good foundation for more complex web development in the future.
(I) The scope of event handler and the propagation of events
Before formally discussing DOM advanced event handling, it is necessary to understand the scope of the event handler. The scope of an event handler is much more complex than that of an ordinary function. Ordinary function scope chains are easier. For example, if you look for a variable a in a normal function, then the JavaScript interpreter will first look for whether there is a variable in the calling object of the function. If not, it will be the next object in the scope chain, generally in the global object. However, event handlers are not that simple, especially defined with HTML attributes. The head of their scope chain is the object that calls them, and the next object is not a global object, but an object that triggers the event handler. This will cause a problem. Both window and document have a method open(). If open() is not modified before, the() method will be called in the event processing function, rather than the commonly used () method, so it should be clearly specified when using it.
(II) Event propagation and registration event handler
1. Event spread
In the secondary DOM standard, event handlers are relatively complex. When an event occurs, the event handler of the target node will be triggered to be executed, but the parent node of the target node also has the opportunity to handle this event. The propagation of an event is divided into three stages. The first is the capture stage. The event propagates from the Document object down the DOM tree to the target node. If any parent node of the target registers a handler for capturing the event, the event will first run the program during the propagation process. The next stage occurs when the target node itself, and the corresponding event handler registered on the target node will be executed; finally, the bubble stage, the event will be uploaded from the target node to the parent node. Similarly, if the parent node has a corresponding event handler, it will be handled. In IE, there is no capture stage, but there is a bubble stage. You can use the stopPropagating() method to stop event propagation, that is, make other elements invisible to this event. In IE 6, cancelBubble is set to true.
2. Register event handler
Like IE, the DOM standard also has its own event handler, but the event handler of the DOM level 2 standard is more powerful than that of IE. The event handler registration uses the addEventListner method. This method has three parameters. The first is the event type, the second is the processed function, and the third is a Boolean value. True means that the formulated event handler will be used to capture events during the event propagation stage, otherwise it will not be captured. When the event occurs on the object, the function that executes this event processing will be triggered, or occurs on the word node of the object, and bubbles upwards on the object, the function that executes this event processing is triggered. For example: ("mousemove",movHandler,true); is to call the moveHandler function when the mousemove event occurs, and the event can be captured.
You can use addEventListener to register multiple event processing programs for an event, but the execution order of these functions is uncertain and is not executed in the registered order like C#.
When registering an event handler with addEventListener in Mozilla Firefox, this keyword represents the document element that calls the event handler, but other browsers do not necessarily do this, because this is not the DOM standard. The correct way is to use the currentTarget attribute to reference the document element that calls the event handler.
3. Event in the secondary DOM standard
Unlike IE, the Event object in W3C DOM is not a property under the window global object. In other words, event is not a global variable. Usually in the DOM secondary standard, event is used as the attribute of the document object where the event occurs. Event contains two sub-interfaces, namely UIEvent and MutationEvent. These two sub-interfaces implement all methods and properties of Event, and the MouseEvent interface is a sub-interface of UIEvent, so it implements all methods and properties of UIEvent and Event. Next, we will take a look at the main properties and methods of Event, UIEvent and MouseEvent.

type: Event type, similar to IE, but does not have a "on" prefix, such as clicking the event is just "click".
target: The node where the event occurred.
CurrentTarget: The node where the event currently being processed occurs may be the node pointed to by the Target attribute, or it may point to the parent node of the node pointed to by the Target due to capture or bubbles.
eventPhase: Specifies the stage of event propagation. It's a number.
timeStamp: The time when the event occurred.
bubbles: Indicate whether the event is bubbled.
cancelable: Indicates whether the event can be cancelled by the preventDefault() method.
preventDefault() method: cancel the default action of the event;
stopPropagation() method: stop event propagation.

view: The window object where the event occurred.
detail: Provides additional information about the event. For click events, mousedown and mouseup events, they all represent the number of clicks.

button: A number that indicates the status of the mouse key in mousedown, mouseup and click events, which is similar to the button attribute in IE, but the meaning of the number is different. 0 represents the left key, 1 represents the middle key, and 2 represents the right key.
altKey, ctrlKey, shiftKey, metaKey: The same as IE, but IE does not have the last one.
clientX, clientY: The meanings of IE are the same, but in the DOM standard, these two attribute values ​​do not take into account the scrolling situation of the document. That is to say, no matter where the document scrolls, as long as the event occurs in the upper left corner of the window, clientX and clientY are both 0. Therefore, in IE, if you want to get the coordinates of the event to the beginning of the document, add the sum.
screenX, screenY: The position of the mouse pointer relative to the upper left corner of the monitor. If you want to open a new window, these two properties are very important.
relatedTarget: Similar to fromElement and toElement in IE, other events have no meaning except for being meaningful to mouseover and mouseout.
(III) Example of dragging DOM elements compatible with two mainstream browsers
Okay, I just talked about so many events in DOM programming and IE. So how do I write a drag and drop program that is compatible with the two mainstream browsers of IE and Mozilla Firefox? The code is as follows:
Copy the codeThe code is as follows:

function beginDrag(elementToDrag,event)
{
  var deltaX=-parseInt();
  var deltaY=-parseInt();

if()
{
  ("mousemove",moveHandler,true);
  ("mouseup",upHandler,true);
}
else if()
{
  ("onmousemove",moveHandler);
  ("onmouseup",upHandler);

}

  if()   ();
  else =true;
  if()  ();
  else =false;

  function moveHandler(e) 
  {
if (!e) e=; //If it is an IE event object, then use
//Global attributes, otherwise use the DOM secondary standard Event object.
    =(-deltaX)+"px";
    =(-deltaY)+"px";

     if()   ();
    else =true;

  }

  function upHandler(e)
  {
       if()
    {
      ("mouseup",upHandler,true);
      ("mousemove",moveHandler,true);}
      else
    {
      ("onmouseup",upHandler);
      ("onmousemove",moveHandler);}
    }
      if()   ();
    else =true;     
  }