Basic theory of events (38)

DOM events

 * [DOM event]


 * 1. What is an event?

 *   An event is an event or a behavior (for an element, many of its events are innate). As long as we operate the element, these behaviors will be triggered

 *   "Events are the inherent behaviors of elements. When we operate elements, we will trigger related event behaviors."


 * 2. Event binding: bind the method to the event behavior inherent in the element. When the event is triggered, the corresponding method will be executed

 *  oBox.οnclick=function(){}


 * 3. Events inherent in the element?

 *   [mouse event]

 *     Click: click (click on the PC side, and click on the mobile side represents click [300 ms delay when the mobile side uses click])

 *     dblclick: double click

 *     mouseover: mouse over

 *     mouseout: mouse out

 *     mouseenter: mouse entry

 *     mouseleave: mouse away

 *     mousemove: mouse movement

 *     mousedown: press the mouse (both the left and right buttons of the mouse work, which is triggered when pressed, and click is triggered when pressed and lifted, and click is triggered only when the down and up are triggered first)

 *     mouseup: mouse up

 *     mousewheel: mouse wheel scrolling

 *    ...


 *   [keyboard event]

 *     keydown: keyboard press

 *     keyup: keyboard up

 *     Keypress: similar to keydown, except that keydown returns the keyboard code and keypress returns the ASCII code value

 *     Input: because the PC has a physical keyboard, it can monitor the pressing and lifting of the keyboard, but the mobile terminal is a virtual keyboard, so keydown and keyup are not available on most mobile phones. We use input events to replace them uniformly (content change events)

 *    ...


 *   [common events of form elements]

 *     Focus: get focus

 *     blur: lose focus

 *     Change: content change

 *    ...


 *   [other common events]

 *     Load: load complete

 *    unload

 *    beforeunload

 *     Scroll: scroll bar scrolling events

 *     resize: size change event   window. ο nresize=function() {} when the browser window size changes, this event will be triggered to execute the corresponding things

 *    ...


 *   [mobile end finger event]

 *     [touch: single finger operation]

 *       touchstart: finger press

 *       touchmove: finger movement

 *       touchend: finger away

 *       touchcancel: the finger operation is cancelled due to an unexpected condition


 *     [gesture: multi finger operation]

 *       gesturestart: finger press

 *       gesturechange: finger change

 *       gestureend: fingers leave

 *    ...


 *   [AUDIO/VIDEO events in H5]

 *     Can play: can play (jamming may occur due to incomplete loading of resources during playback)

 *     Can play through: the resource is loaded and can be played normally without obstacles

 *    ...

Event binding  

 * Event binding

 *   [DOM0 level event binding]

 *     [element].onxxx=function(){}


 *   [DOM2 level event binding]

 *     [element].addEventListener('xxx',function(){},false);

 *     [element].attachEvent('onxxx',function(){}); [IE6~8]


 * Purpose: binding a method to an event of the current element (whether based on DOM0 or DOM2) is to do something (that is, execute the bound method) when triggering the relevant behavior of the element; "Not only the method is executed, but also the browser passes an argument information value = = > which is the event object"

box.onclick = function (ev) {
    //=>Define a formal parameter EV to receive the information value transmitted by the browser when the method is executed (Event object: MouseEvent mouse Event object, KeyboardEvent keyboard Event object, Event ordinary Event object...)
    //=>Many attribute names and values are recorded in the event object. These information contains the basic information of the current operation, such as the X/Y axis coordinates of the mouse click position, who the mouse click on (event source), etc

    // event source (which element is operated on)
    // Ev.clientx/ev.clienty: the X/Y axis coordinate between the current mouse trigger point and the upper left corner of the current window
    // Ev.pagex/ev.pagey: the X/Y axis coordinate of the distance between the current mouse trigger point and the upper left corner of body (first screen)
    // ev.preventDefault(): block default behavior
    // ev.stopPropagation(): prevent bubbling propagation of events
    // ev.type: current event type

    // ev.code: current key 'keyE'
    // ev.key: current key 'e'
    // Ev.which/ev.keycode: the keyboard code of the current key 69
    // let code = ev.which || ev.keyCode;

    //=>Common keyboard codes
     * Left up right down: 37-38-39-40
     * Backspace: 8
     * Enter: 13
     * Space: 32
     * Delete: 46
     * Shift: 16
     * Alt: 18
     * Ctrl: 17
     * ESC: 27
     * F1~F12: 112 ~ 123
     * 48~57: Numeric key
     * 65~90: Lowercase letters

tempInp.onkeydown = function (ev) {
box.onclick = function (ev) {
    //=>In IE browser of lower version, the browser executes the binding method and does not pass in the event object. At this time, ev===undefined needs to be obtained based on window.event (because it is a global attribute, the value of the last operation will be replaced by the mouse every time it operates)
    if (!ev) {
        //=>For the attributes that are not available in the lower version, we can manually set them: first obtain the value according to their own, and then assign it to the new attribute corresponding to the standard (after judgment, the lower version also has TARGET/PAGE-X/PAGE-Y attributes). When they are used later, they can be used directly according to the higher version
        ev = window.event;
        // console.log(ev.srcElement);//=> Ev.srclelement is the source of obtaining events ( is used in the standard) = ev.srcElement;
        // console.log(ev.pageX);//=> pageX/pageY does not exist in the event object of earlier browsers
        ev.pageX = ev.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft);
        ev.pageY = ev.clientY + (document.documentElement.scrollTop || document.body.scrollTop);
        ev.which = ev.keyCode;

        // Preventdefault & stoppropagation are not available in earlier versions
        ev.preventDefault = function () {
            ev.returnValue = false;//=>Older versions block default behavior
        ev.stopPropagation = function () {
            ev.cancelBubble = true;//=>The lower version prevents bubble propagation
    //=>You can use it directly according to the rules of the higher version
    console.log(, ev.which);
box.onclick = function (ev) {
    //=>Who will handle it for whom
    ev = ev || window.event;
    var target = || ev.srcElement;
    ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;

Default behavior and blocking  

 * Default behavior of event: the event itself is innate. Some events trigger, even if you do not have a binding method, there will be some effects. These default effects are "default behavior of event"


 *   The click operation of A tag has A default behavior

 *     1. Page Jump

 *     2. Anchor location (HASH location)


 *      <a href="" target="_blank">

 *           Hello world

 *      </a>

 *       target='_blank ': make it open in a new window


 *      < A href = "#box" > Hello World < / a > first, a HASH value will be set at the end of the URL address bar of the current page. After the browser detects the HASH value, it will locate the box with the same ID and HASH in the current page by default (based on the HASH value, we can also realize SPA single page application)


 *   The INPUT tag also has its own default behavior

 *       1. The input content can be presented in the text box

 *       2. When inputting content, some information previously entered will be presented (not all browsers and in all cases)

 *      ...


 *   The SUBMIT button also has a default behavior

 *       1. Click the button and the page will refresh

 *      <form action="">

            < Input type = "submit" value = "submit" >


        Set ACTION in FORM and click SUBMIT. By default, the page will jump according to the address specified by ACTION, and the information in the FORM will be transferred to the past (in non front and back end separated projects, the server will render the page, and other languages will realize data interaction. This is generally the case)

 //=> How to block default behavior

//1. Prevent the default behavior of A tag: many times we use A tag just to click as an ordinary button to realize A function, without page Jump or anchor positioning


 * Block in structure

 *   < A href = "javascript:;" > the latest full stack video of Everest training is waiting for you~~</a>

 *   javascript:void 0/undefined/null...;


 * It can also be blocked in JS

 *   Bind the CLICK event method. When we CLICK the A tag, the CLICK event will be triggered first, and then our default behavior will be executed


link.onclick = function (ev) {
    ev = ev || window.event;
    return false;

link.onclick = function (ev) {
    ev = ev || window.event;
    ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;

tempInp.onkeydown = function (ev) {
    // ev = ev || window.event;
    // ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;
    return false;
tempInp.onkeydown = function (ev) {
    ev = ev || window.event;

    let val = this.value.trim(),//=>Trim removes the first space in the string (incompatible) this.value=this.value.replace(/^ +| +$/g, '')
        len = val.length;
    if (len >= 6) {
        this.value = val.substr(0, 6);

        //=>Prevent the default behavior from removing special keys (DELETE\BACK-SPACE \ direction keys...)
        let code = ev.which || ev.keyCode;
        if (!/^(46|8|37|38|39|40)$/.test(code)) {
            ev.preventDefault ? ev.preventDefault() : ev.returnValue = false;

  Event propagation mechanism

*Event propagation mechanism

 *   Bubble propagation: trigger an event (click event) behavior of the current element. Not only the event behavior of the current element will be triggered, but also the related event behavior of its ancestor elements will be triggered in turn. This mechanism is the "bubble propagation mechanism of events"

 * xxx.onxxx=function(){}   DOM0 event binding binds methods to the event behavior of the element. These methods are executed in the bubbling phase (or target phase) of the current element event behavior


 * xxx.addEventListener('xxx',function(){},false)   The third parameter FALSE also controls the binding method to be executed in the bubbling stage (or target stage) of event propagation; Only when the third parameter is TRUE, it means that the current method will trigger execution in the capture phase of event propagation (this capture phase execution has no practical significance and is not used in the project)

 * Different browsers have different definitions of the outermost ancestor element

 *     Google: window - > document - > HTML - > body

 *     IE high: window - > HTML - > body

 *     IE low: HTML - > body

let aa = null;
document.body.onclick = function(ev) {
    console.log('body', ev, ev === aa); //=>TRUE

outer.onclick = function(ev) {
    console.log('outer', ev, ev === aa); //=>TRUE

inner.onclick = function(ev) {
    /*ev = ev || window.evenet;
    ev.stopPropagation ? ev.stopPropagation() : ev.cancelBubble = true;*/
    aa = ev;
    console.log('inner', ev);

*Some understanding of event object

 *   1. The event object is used to store the relevant information of the current operation, which is related to the operation and not necessarily related to the element

 *   2. When we operate based on mouse or keyboard, the browser will store the information of this operation (the standard browser is stored in the default memory (I can't find it), and the lower version of IE is stored in window.event). The stored value is an object (heap memory); The operation will certainly trigger a certain behavior of the element and execute the bound method. At this time, the standard browser will pass the previously stored object (to be exact, the heap memory address) as an argument to each executed method. Therefore, even if there are EV s in more methods, the stored value is one (only the object of this operation information)

  The difference between mouseenter and mouseover

 * What is the difference between mouseenter and mouseover?

 *   1.over is a slip (overwrite) event. It enters the child element from the parent element. If it leaves the parent element, it will trigger the out of the parent element and trigger the over of the child element

 *     Entry belongs to entry. Entering a child element from a parent element does not mean leaving the parent element. It will not trigger the leave of the parent element and trigger the entry of the child element


 *   2.enter and leave prevent the bubbling propagation of events, while over and out still have the possibility of bubbling propagation


 * Therefore, when the parent element embeds the child element, many things do not want to be operated when using OVER. At this time, it will be easier and convenient to use ENTER. Therefore, in real projects, ENTER will be used more than OVER

Keywords: Javascript html5 html

Added by cactuscake on Mon, 11 Oct 2021 04:48:25 +0300