English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Daily Must-Learn Events in JavaScript

In fact, this article was written quite a while ago, but due to a bug in SF's save function, I wrote a lot at that time, only to find that it was not saved, and I felt that it was a great regret that it was not finished. Today, I happen to have some free time, so I will supplement it, and it is also a good opportunity to complete my JavaScript learning summary. 

Here, let's mainly discuss the events related to JavaScript - 

Event handler 

In the DOM, some events are defined, and the function that responds to an event is called an event handler (or event listener). The name of an event handler usually starts with 'on', for example: onclick, etc. 

Event bubbling and capturing 

Event flow refers to the order in which events are received on a page, IE, Firefox, and Chrome browsers all use event bubbling. What is event bubbling refers to the fact that the event is initially received by the most specific element, and then propagates to less specific nodes level by level. On the contrary, event capturing is proposed by Netscape, and the specific diagram of event bubbling and capturing is as follows:

 

Although event capturing is the only event stream model supported by Netscape, currently IE9, and Firefox and Google also support this event stream model. 

The benefits of event bubbling 

Because events have a bubbling mechanism, we can use the principle of bubbling to add events to the parent level and trigger the execution effect. The advantage of doing so is of course to improve performance.

 <head lang="en">
 <meta charset="UTF-8">
 <title></title>
 <script type="text/javascript">
 window.onload = function () {
  var aUl = document.getElementsById("bubble");
  var aLi = aUl.getElementsByTagName("li");
  for(var i = 0;i<aLi.length;i++){
  aLi[i].onmouseover = function () {
   this.style.backgroundColor = "blue";
  };
  ali[i].onmouseout = function () {
   this.style.backgroundColor = "";
  }
  }
 };
 </script>
</head>
<body>
<div>
 <ul id = "bubble">
 <li>1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 </ul>
</div>
</body> 

This allows us to add mouse events to the li elements. However, if we have many li elements and use a for loop, it may affect performance. 

We can achieve this effect using event delegation. The HTML remains unchanged:

 <script type="text/javascript">
 window.onload = function () {
 var aUl = document.getElementsById("bubble");
 var aLi = aUl.getElementsByTagName("li");
 //In any event, as long as the element you are operating on is the event source.
 // IE: window.event.srcElement
 // Standard: event.target
 aUl.onmouseover = function (ev) {
  var ev = ev || window.event;
  var target = ev.target || ev.srcElement;
  if(target.nodeName.toLowerCase() == "li"){
  target.style.background = "blue";
  }
 };
 aUl.onmouseout = function (ev) {
  var ev = ev || window.event;
  var target = ev.target || ev.srcElement;
  if(target.nodeName.toLowerCase() = "li"){
  target.style.background = "";
  }
 }
 };
</script> 

How to prevent event bubbling? Let's see an example below:

 <div onclick="showMsg(this,event)" id="outSide" style="width:100px; height:100px; background:#000; padding:50px">
<div onclick="showMsg(this,event)" id="inSide" style="width:100px; height:100px; background:#CCC"></div>
</div>
<script type="text/javascript">
//After preventing the event bubble, when you click the gray box, the dialog box will pop up only once in the entire process (note the difference from the default case)
function showMsg(obj,e)
{
 alert(obj.id);
 stopBubble(e)
}
//Prevent event bubble function
function stopBubble(e)
{
 if (e && e.stopPropagation)
 e.stopPropagation()
 else
 window.event.cancelBubble=true
}
</script> 

Click the black outer effect map:

 

DOM 0-level event handler 

Specifying event handlers with JavaScript usually involves assigning a callback function to the property of this event handler. Each element has its own event handler property (property in lowercase, such as: onclick)

 btn.onclick = function(){
 console.log('hello');
}; 

Using DOM 0-level event handlers is considered a method of the element. Therefore, this points to the current element:

 var btn = document.getElementById('myDiv');
//Events triggered on the DOM will generate an event object event
btn.onclick = function (event) {
 alert(this.id);//myDiv 
}; 

DOM level 1

DOM level 1 Focuses on the HTML and XML document model. It contains document navigation and processing functions. 

DOM level 1 On 1998 Year 10 Month 1 Day became W3C recommended standard. 

The second draft of the work in 2000 Year 9 Month 29 Day. 

It is worth mentioning that DOM level 0 is not W3C specification. It is simply a specification in Netscape Navigator 3.0 and IE 3.0 is an equivalent functional definition of. 

DOM 2.Event handler 

DOM 2Define two methods to specify and delete the operation of event handlers: addEventListener() and removeEventListener(), both of which accept three parameters:

1.Event name. For example, the above click.
2.As a function of the event handler.
3.Boolean value (true indicates that the event handler is called during the capture phase, false indicates the bubble phase).

Through the addEventListener method of the Element object, callback functions for events can also be defined.

 //element.addEventListener(event, function, useCapture)
var btn = document.getElementById('myDiv');
btn.addEventListener('click', function () {
 console.log(this.id);
},false); 

Event handlers in IE 

IE9Previous IE browsers did not support addEventListener() and removeEventListener(). 

Unlike other browsers, IE uses the attachEvent() and detachEvent() methods to add event handlers to the DOM, since IE8And earlier versions only support event bubbling, so they only accept two parameters:
1、Event handler name (the prefix 'on' must be added)
2、Event handler function
The event handler added using attachEvent() is as follows:

 var btn = document.getElementById('myDiv');
btn.attachEvent('onclick', function () {
 console.log(this.id);
}); 

It is worth noting that in the case of using the attachEvent() method, the event handler runs in the global scope, so this equals window at this time 

Event object
 
When an event is triggered on a DOM element, an event object named event is generated, which contains all information related to the event. This includes the element that caused the event, the type of the event, and other information related to the specific event. The event object is passed as the first parameter to the callback function that listens to the event. We can use this event object to obtain a large amount of information related to the current event:
 type (String) — The name of the event
target (node) — The DOM node where the event originated
currentTarget?;(node) — The current callback function is triggered by the DOM node (a more detailed introduction will be provided later)
bubbles (boolean) — Indicates whether this event is a bubbling event (an explanation will be provided later)
preventDefault(function) — This method prevents the user agent in the browser from triggering the default behavior related to the current event. For example, it can prevent the click event of an <a> element from loading a new page
cancelable (boolean) — This variable indicates whether the default behavior of this event can be prevented by calling event.preventDefault.
stopPropagation (function) — Cancel the further capture or bubbling of the event, use this method when bubbles is true
eventPhase:Returns a number representing the current stage of the event, 0 means the event is beginning to propagate from the DOM surface to the target element,1For the capturing phase,2For the event to reach the target element,3For the bubbling phase.

In addition, the event object may also have many other properties, but they are all specific to the event. 

In addition, the stopPropagation() method is used to immediately stop the propagation of the event in the DOM, i.e., to cancel further event bubbling or capturing.

 var btn = document.getElementById('myDiv');
btn.onclick = function (event) {
 alert("clicked");
 event.stopPropagation();
};
//Avoid triggering event handlers on document.body
document.body.onclick = function (event) {
 alert("Body clicked"); 
}; 

The event object only exists during the execution of the event handler, and it will be automatically destroyed once the event handler has been executed. 

IE event object 

When adding event handlers at the DOM level 0, the event object exists as a property of the window object:

 var btn = document.getElementById('myDiv');
btn.onclick = function (event) {
 var event = window.event;
 alert(event.type);//click
}; 

The event object of IE also contains properties and methods related to the event that created it.
cancleBubble Boolean   The default value is false, but it can be set to true to cancel event bubbling, the same as the stopPropagation() method in dom.
returnValue   Boolean   The default value is true, when set to false, it is used to cancel the default behavior of the event, the same as preventDefault() in dom.
srcElement  Element  The target of the event, the same as the target attribute in dom.
type     String   The type of event triggered.

click event 

After the user clicks, the event object will contain the following properties.
 pageX, pageY: The coordinates of the click position relative to the html element, in units of pixels.
clientX, clientY: The coordinates of the click position relative to the viewport (viewport), in units of pixels.
screenX, screenY: The coordinates of the click position relative to the device display screen, in units of the device hardware pixels

clientX, clientY 

Illustration: clientX and clientY, their values represent the horizontal and vertical coordinates of the mouse pointer in the viewport at the time of the event (without the scrollbar area)

offset

By the following4properties that can obtain the offset of the element.

   (1offsetHeight: The space size occupied by the element vertically, in pixels. It includes the height of the element, the height of the (visible) horizontal scrollbar, the top border height, and the bottom border height.

   (2offsetWidth: The space size occupied by the element horizontally, in pixels. It includes the width of the element, the width of the (visible) vertical scrollbar, the left border width, and the right border width.

   (3offsetLeft: The pixel distance between the left outer edge of the element and the left inner edge of the containing element.

   (4offsetTop: The pixel distance between the top outer edge of the element and the top inner edge of the containing element.

pageX, pageY 

These two properties represent the position of the mouse cursor in the page, and in the case where there is no page scroll, the values of pageX, pageY are equal to the values of clientX, clientY 

scroll size 

scroll size, which refers to the size of the element containing the scrollable content.

    The following is4properties related to scroll size.

   (1scrollHeight: The total height of the element's content without a scrollbar.

   (2scrollWidth: The total width of the element's content without a scrollbar.

   (3scrollLeft: The number of pixels that the content area is hidden to the left. By setting this property, you can change the scroll position of the element.

   (4scrollTop: The number of pixels that the content area is hidden above. By setting this property, you can change the scroll position of the element.

focus events 

Focus events are triggered when page elements gain or lose focus, and there are the following4focus events:
 1.blur: This event is triggered when an element loses focus, and the event does not bubble.
 2.focus: This event is triggered when an element gains focus, and it does not bubble.
 3.focusin: This event is triggered when an element gains focus, and it bubbles.
 4.focusout: This event is triggered when an element loses focus, and it bubbles. 

mouse events 

DOM 3Level defines9mouse events:
 click: This event is triggered when the user clicks the primary mouse button, usually the left mouse button or the Enter key.

dbclick: This event is triggered when the user double-clicks the mouse.

mousedown: This event is triggered when the user presses any mouse button, and it cannot be triggered by the keyboard.

mousemove: Triggered repeatedly when the mouse moves around an element, and this event cannot be triggered by keyboard events.

mouseout: Triggered when the mouse leaves the element, and this event cannot be triggered by the keyboard.

mouseover: Triggered when the mouse enters the element, and this event cannot be triggered by the keyboard.

 mouseenter: Similar to 'mouseover', but does not bubble, and it is not triggered when the cursor moves to the descendant elements.

mouseleave: Similar to 'mouseout', but does not bubble. It is not triggered when the cursor is above the element.

mouseup: Triggered when the user releases the mouse button, and cannot be triggered by the keyboard.

The event object passed to the mouse event handler has clientX and clientY properties, which specify the position of the mouse pointer relative to the containing window. By adding the scroll offset of the window, the mouse position can be converted to document coordinates.
All elements on the page support mouse events. In addition to mouseenter and mouseleave, all events bubble, and their default behavior can be canceled. However, canceling the default behavior of mouse events may affect other events because some mouse events are interdependent.

Drag events 

(1)drag event
 The drag event is triggered during the dragging process of the source object.
(2)dragstart, dragend event
 The dragstart event is triggered when the user starts dragging an object with the mouse, and the dragend event is triggered when dragging ends.
(3)dragenter, dragleave event
 The dragenter event is triggered on the target object when the source object is dragged into the target object. The dragleave event is triggered on the target object after the source object leaves the target object.
(4)dragover event
 The dragover event is triggered on the latter when the source object is dragged over another object.
(5)drop event

 When the source object is dragged to the top of the target object and the user releases the mouse, the drop event is triggered on the target object.

That's all for this article. I hope it helps with your learning, and I also hope everyone will support the Yell Tutorial.

You May Also Like