WebApi notes_ 2_ Event advanced

Event advanced

1. Registration event (binding event)

1.1 overview of registration events

Adding an event to an element is called a registration event or a binding event.

There are two ways to register events: traditional method and method listening registration method.

Traditional registration method:

  • Use the event onclick starting with on
  • <button ╬┐nclick="alret('hi~')">
  • btn.╬┐nclick=function(){}
  • Features: uniqueness of registration events

Method listening registration method:

  • w3c standard recommendation
  • addEventListener(), which is a method
  • Ie before IE9 does not support this method. attachEvent() can be used instead
  • Features: multiple listeners can be registered for the same element and event
  • Execute in order of registration

1.2 addEventListener

eventTarget.addEventListener(type,listener[,useCapture])

The eventTarget.addEventListener() method registers the specified listener with the eventTarget (target object). When the object triggers the specified event, the event handling function will be executed.

The method receives three parameters:

  • Type: event type string, such as click and mouseover. Note that on is not allowed here
  • listener: event handling function, which will be called when an event occurs
  • useCapture: optional parameter. It is a Boolean value. The default value is false. After learning the DOM event flow, we will learn further
<body>
    <button>Traditional registration events</button>
    <button>Method monitoring and registration practice</button>
    <script>
        var btns = document.querySelectorAll('button');
        // 1. The traditional way of registering events only executes the last event handler bound
        btns[0].onclick = function() {
            alert('hi~')
        }
        btns[0].onclick = function() {
                alert('R U ok~')
            }
            // 2. The event type in the event listening registration event addEventListener is a string
            //  Multiple listeners (event handlers) can be added to the same element and the same event
        btns[1].addEventListener('click', function() {
            alert('22');
        })
        btns[1].addEventListener('click', function() {
            alert('33');
        })
    </script>
</body>

1.3 attachEvent event listening method (non-standard)

eventTarget.attachEvent(eventNameWithOn, callback)

The eventTarget.attachEvent() method registers the specified listener with the eventTarget (target object). When the object triggers the specified event, the specified callback function will be executed.

The method receives two parameters:

  • eventNameWithOn: event type string, such as onclick and onmouseover, with on
  • Callback: event handling function. When the target triggers an event, the callback function is called

Note: IE8 and earlier versions support

2. Delete event (unbind event)

2.1 method of deleting events

  • Traditional registration method

    eventTarget.onclick = null;
    
  • Method listening registration method

    eventTarget.removeEventListener(type, listener[, useCapture]);
    
    eventTarget.detachEvent(eventNameWithOn, callback); // Before ie8
    
<body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <script>
        var divs = document.querySelectorAll('div');
        divs[0].onclick = function() {
                alert('11');
                // 1. Delete events in traditional way
                divs[0].onclick = null;
            }
        //2. Method listens for deletion events in registration mode. Note: anonymous functions cannot be used here
        divs[1].addEventListener('click', fn);

        function fn() {
            alert('22');
            divs[1].removeEventListener('click', fn);
        }
    </script>
</body>

3. DOM event flow

Event flow describes the order in which events are received from the page.
When an event occurs, it will propagate between element nodes in a specific order. This propagation process is DOM event flow.

DOM event flow is divided into three stages:

  1. Capture phase
  2. Current target stage
  3. bubbling phase

  • Event bubbling: IE first proposed that an event is received by the most specific element at the beginning, and then propagated level by level to the top node of DOM.
  • Event capture: Netscape was first proposed. It starts from the top-level node of DOM, and then propagates level by level down to the process of receiving the most specific elements.

We throw a stone into the water. First, it will have a descent process, which can be understood as the capture process from the top to the most specific element (target point) of the event; After that, bubbles will be generated and float to the water after the lowest point (the most specific element). This process is equivalent to event bubble.

be careful

  1. Only one stage of capture or bubbling can be executed in JS code.
  2. onclick and attachEvent can only get the bubbling phase.
  3. addEventListener(type, listener[, useCapture]) if the third parameter is true, it means to call the event handler in the event capture phase; If it is false (the default is false if it is not written), it means that the event handler is called in the event bubbling stage.
  4. In actual development, we seldom use event capture, and we pay more attention to event bubbling.
  5. Some events do not bubble, such as onblur, onfocus, onmousenter, onmousesave
  6. Event bubbling sometimes brings trouble, and sometimes helps to do some events skillfully. We'll explain it later.
<body>
    <div class="father">
        <div class="son">son Box</div>
    </div>
    <script>
        // Three phases of DOM event flow
        // 1. JS code can only execute one of the capture or bubble phases.
        // 2. onclick and attachEvent (ie) can only get the bubbling stage.
        // 3. In the capture phase, if the third parameter of addEventListener is true, it is in the capture phase    
        // document -> html -> body -> father -> son
        var son = document.querySelector('.son');
        son.addEventListener('click', function() {

            console.log('son');
        }, true);
        var father = document.querySelector('.father');
        father.addEventListener('click', function() {

            console.log('father');
        }, true);
        // 4. In the bubbling phase, if the third parameter of addEventListener is false or omitted, it is in the bubbling phase  
        // son -> father -> body -> html ->document
        var son = document.querySelector('.son');
        son.addEventListener('click', function() {

            console.log('son');
        }, false);
        var father = document.querySelector('.father');
        father.addEventListener('click', function() {

            console.log('father');
        }, false);
    </script>
</body>

4. Event object

4.1 what is the event object

Official explanation: the event object represents the state of the event, such as the state of the keyboard keys, the position of the mouse, and the state of the mouse buttons.
Simple understanding: after an event occurs, the collection of a series of information data related to the event is put into this object. This object is the event object event, which has many properties and methods.

<body>
    <div>123</div>
    <div>123</div>
    <script>
        // Event object
        var divs = document.querySelectorAll('div');
            // 1. event is an event object written into the parentheses of our listening function
            // 2. The event object can exist only when there is an event. It is automatically created by the system and does not need to pass parameters
            // 3. The event object is a collection of a series of related data of our events, which are related to events. For example, when a mouse clicks, it contains the relevant information of the mouse,
            // 4. Event objects can be named by ourselves, such as event and e
            // 5. The event object also has compatibility problems ie678 through window.event
        divs[0].onclick = function(event) {      
            console.log(event);
        }
        divs[1].addEventListener('click', function(event) {
            console.log(event);
        })
    </script>
</body>

4.2 common attributes and methods of event objects

e. The difference between target and this:

<body>
    <div>123</div>
    <ul>
        <li>abc</li>
        <li>abc</li>
        <li>abc</li>
    </ul>
    <script>
        // Properties and methods of common event objects
        // 1. e.target returns the object (element) that triggered the event 
        //    this returns the object (element) that binds the event
        var div = document.querySelector('div');
        div.addEventListener('click', function(e) {
            console.log(e.target);
            console.log(this);
        })
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) {
            // If we bind an event to ul, this points to ul
            console.log(this); // ul
            // e.target points to the object we clicked on. Who triggered this event
            console.log(e.target); //li
        })
    </script>
</body>

Event object block default behavior:

<body>
    <div>123</div>
    <a href="http://Www.baidu.com "> Baidu</a>
    <form action="http://www.baidu.com">
        <input type="submit" value="Submit" name="sub">
    </form>
    <script>
        // Properties and methods of common event objects
        // 1. Return event type
        var div = document.querySelector('div');
        div.addEventListener('click', fn);

        function fn(e) {
            console.log(e.type);    //  click
        }
        // 2. Block the default behavior (event) so that the link does not jump or the submit button does not submit
        var a = document.querySelector('a');
        a.addEventListener('click', function(e) {
            e.preventDefault(); // This method prevents default event behavior, such as not letting links jump, etc
        })
        a.onclick = function() {
            // We can also use return false to block the default behavior. There is no compatibility problem, but the returned code will no longer be executed
            return false;
        }
    </script>
</body>

5. Prevent event bubbling

5.1 two ways to prevent event bubbling

Event bubbling: it is initially received by the most specific element, and then propagated up to the top node of the DOM level by level.
The characteristics of event bubbling will bring both disadvantages and benefits, which we need to master flexibly

Prevent event bubbling

  • Standard writing method: use the stopPropagation() method in the event object
    e.stopPropagation()
  • Nonstandard writing: IE 6-8 uses the cancelBubble attribute of the event object
    e.cancelBubble = true;
<body>
    <div class="father">
        <div class="son">son Box</div>
    </div>
    <script>
        // Properties and methods of common event objects
        // Stop bubbling DOM recommended standard stopPropagation()
        var son = document.querySelector('.son');
        son.addEventListener('click', function(e) {
            console.log('son');
            e.stopPropagation(); //Stop bubbling
        }, false);
        var father = document.querySelector('.father');
        father.addEventListener('click', function() {
            console.log('father');
        }, false);
        document.addEventListener('click', function() {
            console.log('document');
        })
    </script>
</body>

6. Event entrustment (agency, delegation)

The characteristics of event bubbling will bring both disadvantages and benefits, which we need to master flexibly. There are the following scenes in life:

There are 100 students in our class and 100 couriers. It takes a long time to send them one by one. At the same time, each student also needs to queue up to get it, which also takes a long time. What?

Solution: the couriers entrust 100 couriers to the head teacher. The head teacher puts these couriers in the office and the students can get them by themselves after class.

Advantages: the courier saves trouble and can leave when entrusted to the head teacher. It is also convenient for students to get it, because they believe in the head teacher.

  • Event delegation

    • Event delegation is also called event proxy, which is called event delegation in jQuery.
  • Principle of event delegation

    • Instead of setting the event listener for each child node separately, the event listener is set on its parent node, and then the bubble principle is used to affect the setting of each child node.
    • The above case: register the click event for ul, and then use the target of the event object to find the currently clicked li. Because clicking li, the event will bubble on ul. If ul has a registered event, the event listener will be triggered.
  • Role of event delegation

    • We only operated the DOM once, which improved the performance of the program.
<body>
    <ul>
        <li>literary jargon</li>
        <li>literary jargon</li>
        <li>literary jargon</li>
        <li>literary jargon</li>
        <li>literary jargon</li>
    </ul>
    <script>
        // The core principle of event delegation: add a listener to the parent node and use event bubbling to affect each child node
        var ul = document.querySelector('ul');
        ul.addEventListener('click', function(e) {
            console.log('123');
            e.target.style.backgroundColor = 'pink';
        })
    </script>
</body>

7. Common mouse events

7.1 common mouse events

  • Disable right mouse button menus
    contextmenu mainly controls when the context menu should be displayed. It is mainly used by programmers to cancel the default context menu.
<body>
    I am a text that I don't want to share
    <script>
        // 1. contextmenu we can disable the right button
        document.addEventListener('contextmenu', function(e) {
            e.preventDefault(); //Cancel default event
        })
    </script>
</body>
  • Disable mouse selection (selectstart starts selection)
<body>
    I am a text that I don't want to share
    <script>
        // 2. The text selectstart cannot be selected
        document.addEventListener('selectstart', function(e) {
            e.preventDefault();
        })
    </script>
</body>

7.2 mouse event object

Event object represents the state of an event and a collection of a series of information related to the event. At this stage, we mainly use mouse event object MouseEvent and keyboard event object KeyboardEvent.

<body>
    <script>
        // Mouse event object MouseEvent
        document.addEventListener('click', function(e) {
            // 1. X and Y coordinates of the client mouse in the visual area
            console.log(e.clientX);
            console.log(e.clientY);
            // 2. The page mouse is on the X and Y coordinates of the page document
            console.log(e.pageX);
            console.log(e.pageY);
        })
    </script>
</body>

Cases of following the mouse:

  1. The mouse moves continuously. Use the mouse to move the event: mousemove
  2. Move in the page and register the event for document
  3. The picture should move a distance without occupying a position. We can use absolute positioning
  4. Core principle: each time the mouse moves, we will get the latest mouse coordinates. Take the x and y coordinates as the top and left values of the picture to move the picture
<style>
        img {
            position: absolute;
        }
</style>
<body>
    <img src="http://md.gitnote.cn/WebApi notes_ 2_ Event advanced - 2021924104851. PNG "ALT =" ">
    <script>
        var pic = document.querySelector('img');
        document.addEventListener('mousemove', function(e) {
            // mousemove is triggered as soon as the mouse moves
            var x = e.pageX;
            var y = e.pageY;
            pic.style.left = x - 50 + 'px';
            pic.style.top = y - 50 + 'px';
        })
    </script>
</body>

8. Common keyboard events

8.1 common keyboard events

Events can be triggered not only with the mouse, but also with the keyboard.

<body>
    <script>
        // Common keyboard events
        // 1. Triggered when the Keyup button pops up
        document.onkeyup = function() {
                console.log('I'm up!');
            }
            // 2. Triggered when the Keydown key is pressed
        document.onkeydown = function() {
                console.log('I pressed it!');
            }
            // 3. When the keypress key is pressed, the unrecognized function key ctrl shift is triggered
        document.onkeypress = function() {
                console.log('I pressed press!');
            }
            // 4. Execution sequence of three events keydown keypress keyup
    </script>
</body>

8.2 keyboard event object

be careful:

  • onkeydown and onkeyup are case insensitive, and onkeypress is case sensitive.
  • In our actual development, we use keydown and keyup more, which can identify all keys (including function keys)
  • Keypress does not recognize function keys, but the keyCode attribute is case sensitive and returns different ASCII values
<body>
    <script>
        // The keyCode property in the keyboard event object returns the ASCII code value of the pressed key
        document.addEventListener('keyup', function(e) {
            console.log(e);
            console.log(e.keyCode);
            // 1. Our keyup and keydown events are not case sensitive. Both A and A get A:65
            // 2. Our keypress event is case sensitive a:97 A:65
        })
    </script>
</body>

Simulated JD key input case:

  1. Core idea: check whether the user has pressed the s key. If the user presses the s key, the cursor will be positioned in the search box
  2. Use the keyCode in the keyboard event object to judge whether the user pressed the s key
  3. Search box to get focus: use the focus() method in js
<body>
    <input type="text" name="" id="">
    <script>
        var search = document.querySelector('input');
        document.addEventListener('keyup', function(e) {
            if (e.keyCode === 83) {
                search.focus();
            }
        })
    </script>
</body>

Statement:
This article is a summary of my study of the relevant courses of dark horse. Part of the content of the article is intercepted from the ppt provided by dark horse.

Keywords: Javascript html5 html

Added by capbiker on Sat, 25 Sep 2021 03:43:07 +0300