Full parsing of DOM operation event syntax (GIF dynamic diagram, code combination can be seen)

catalogue

1, Three elements of event binding

1.1 # label object

1.2 event type

1.3 event handling function

1.4 event binding syntax form

1.4.1 # grammatical form I

1.4.2} grammatical form II

1.4.3 differences between on syntax and event listening syntax

1.5 event binding syntax compatibility

1.5.1 # standard browser

1.5.2 # lower version IE browser

2, Event deletion

2.1 deletion of on syntax binding event

2.2 deleting event listening syntax

3, Blocking of default events

3.1 definition

3.2. Block default events

3.3 compatibility

3.3.1 # standard browser

3.3.2 # low version IE browser

4, Prevent propagation of events / prevent bubbling events

4.1 definition

4.2 prevent event propagation syntax

4.3 compatibility

4.3.1 # standard browser

4.3.2 # low version IE browser

5, Common event types

5.1 window related event types

5.2 # mouse related event types

5.3 # keyboard related event types

5.3.1} event type

5.3.2} compatibility

5.3.3 # precautions

5.4} related event types of the form

5.5 mobile terminal events

5.6 special events

6, Coordinates in event Click

6.1 , coordinates relative to the upper left corner of the tag object that triggered the event

6.2 coordinates relative to the upper left corner of the window

6.3 coordinates relative to the upper left corner of the HTML page

7, Event object event

7.1 definition

7.2 syntax

8, Event delegation

8.1 definition

8.2 syntax

8.3 advantages

1, Three elements of event binding

1.1 # label object

The event source is the label object that binds the event

1.2 event type

That is, the type of event bound to the label object, such as "click"

1.3 event handling function

That is, the function executed when the event is triggered is the syntax form of callback function, which can be function name or anonymous function. For example, "function() {}".

1.4 event binding syntax form

1.4.1 # grammatical form I

Event listener tag object addEventListener( 'click' , function(){})

1.4.2} grammatical form II

Bind label objects with on syntax onclick = function(){}

1.4.3 differences between on syntax and event listening syntax

The on syntax is an event handler bound by a = equal assignment

= equal assignment essentially performs an override assignment

The data after assignment will overwrite the previously stored data

That is, the on syntax is the same event type as a label object

Only one event handler can be bound by assignment

If the assignment is bound to multiple event handlers

The post assigned event handler will overwrite the event handler stored between

Finally, execute the last event handler

Code demonstration:

<body>
    <div>click</div>
    <script>
        const oDiv = document.querySelector("div");
        // The first grammatical form
        oDiv.addEventListener("click",function(){
            console.log("Da Congming code nongxu");
        })
        // The second grammatical form
        oDiv.onclick = function(){console.log("Da Congming code nongxu");}
        // =Equal assignment essentially performs an override assignment
        // Execute the last event handler
        oDiv.onclick = function(){console.log(666666);}
    </script>
</body>

Operation results: 

1.5 event binding syntax compatibility

1.5.1 # standard browser

Label object addEventListener( 'click' , function(){})   

1.5.2 # lower version IE browser

Label object attachEvent('onclick' , function(){});

2, Event deletion

2.1 deletion of on syntax binding event

Label object on event type = null;

Label object on event type = function() {};

When the event is triggered, there is no function program called for execution

Achieve the effect of deleting events

2.2 deleting event listening syntax

You need to call a special delete function method

Label object removeEventListener('event type ', event handler);

Label object Detachevent ('on 'event type, event handling function);

Note: use special function methods to delete the bound event handling function. Only the bound function name can be deleted, and the bound anonymous function cannot be deleted

Code demonstration:

<body>
    <div>click</div>
    <script>
        const oDiv = document.querySelector("div");
        // Use special function methods to delete bound event handlers
        //  Only bound function names can be deleted. Bound anonymous functions cannot be deleted

        // Define function
       function fun(){
        console.log("Da Congming code nongxu");
       }
        //Callback function call function
        oDiv.addEventListener("click",fun);
         // Only bound function names can be deleted
        oDiv.removeEventListener("click",fun);

        // Cannot delete bound anonymous functions
        // Therefore, the background output 123456789 will still be executed
        oDiv.addEventListener("click",function(){
            console.log(123456789);
        })
        oDiv.removeEventListener("click",function(){
            console.log(123456789);
        })

        oDiv.onclick = function(){console.log("Da Congming code nongxu");}
// on syntax binding event deletion
        oDiv.onclick = null;


    </script>
</body>

Operation results:

 

3, Blocking of default events

3.1 definition

Click jump of a tag, click Submit of form tag and right-click menu are all default events

3.2. Block default events

Define a formal parameter in the event handler function. The formal parameter name is generally e / event

Label object addEventListener('event type '), function (E / event){

/ / prevent default event execution

Formal parameters preventDefault() ;

    })

Code demonstration:

<body>
    <script>
        // Get label object
        const oBody = document.querySelector("body");
        // contextmenu right click event  
        oBody.addEventListener("contextmenu",function(e){
            // The background output ensures that the event is triggered
            console.log("The right mouse button has been pressed");
            // Right click on the normal web page and there will be a menu
            // After the default event is blocked, no menu will be generated
            e.preventDefault() ;
        })
    </script>
</body>

Operation results:

 

3.3 compatibility

3.3.1 # standard browser

        e.preventDefault() ;

3.3.2 # low version IE browser

        e.returnValue = false;

4, Prevent propagation of events / prevent bubbling events

4.1 definition

The parent tag and the descendant tag add events of the same type, and the descendant tag triggers events. The parent tag will also trigger events of the same type. This implementation principle is called event propagation / bubbling event.

4.2 prevent event propagation syntax

Label object Addeventlistener (event type, function(e / event){

        e.stopPropagation();

    })

Code demonstration:

<body>
    <div>
        <h1></h1>
    </div>
    <script>
        // Get label object
        const oDiv = document.querySelector("div");
        const oH = oDiv.querySelector("h1");
        // Add click event to div
        oDiv.addEventListener("click",function(){
            console.log("You clicked div label");
            
        })
        // Add click event to h1
        oH.addEventListener("click",function(e){
            console.log("You clicked h1 label");
         // Event propagation blocking
            e.stopPropagation();
        })
    </script>
</body>

Operation results:

Before blocking: click the h1 tag, and the div click event will also be triggered

After blocking: clicking h1 will only execute the events of h1.

4.3 compatibility

4.3.1 # standard browser

        e.stopPropagation();

4.3.2 # low version IE browser

        e.cancelBubble = true ;

5, Common event types

5.1 window related event types

window.addEventListener( 'resize' , function(){} )  Browser window size listening event
window.addEventListener( 'scroll' , function(){} )  Page scrolling listening event
window.addEventListener( 'load' , function(){} )    Browser load event
window.open(url address)New window opens URL link
window.open (URL address)Close current window

document.addEventListener('visibilitychange')

document. The query value of visibilitystate is hidden/visible

Minimize window listening events

The first five attributes have been explained in detail in my previous blog. Please check previous blogs. Here we mainly demonstrate the last window to minimize listening events.

Demo code:

<body>
    <script>
        document.addEventListener("visibilitychange",function(){
            
            console.log(document.visibilityState);
        })
    </script>
</body>

Operation results:

 

5.2 # mouse related event types

click          Left click

dblclick

Double click with the left mouse button
contextmenu  Right click
mousedown  Press the mouse button
mouseup  Lift the mouse button
mouseover  Mouse in
mouseout    Mouse out
mouseenter  Mouse in
mouseleave  Mouse out

Code demonstration:

<body>
    <div></div>
    <script>
        const oDiv = document.querySelector("div");
        oDiv.addEventListener("click",function(){
            console.log("Left click");
        })
        oDiv.addEventListener("dblclick",function(){
            console.log("Double click with the left mouse button");
        })
        oDiv.addEventListener("contextmenu",function(){
            console.log("Right click");
        })
        oDiv.addEventListener("mousedown",function(){
            console.log("Press the mouse button");
        })
        oDiv.addEventListener("mouseup",function(){
            console.log("Lift the mouse button");
        })
    </script>
</body>

Operation results:

Note:

mouseover mouse in mouseout mouse out. Triggered once when it passes through the boundary of the label object, and the event will also be triggered if it is labeled for the descendants of the current event.

mouseenter , mouse in , mouseleave , mouse out. Triggered once when it passes through the boundary of the label object. Adding an event to the current label and a descendant label will not trigger an event.

Demo code:

<body>
    <div>
        <h1></h1>
    </div>
    <script>
        const oDiv = document.querySelector("div");
        oDiv.addEventListener("mouseover",function(){
            console.log("Mouse in");
        })
        oDiv.addEventListener("mouseout",function(){
            console.log("Mouse out");
        })
        oDiv.addEventListener("mouseenter",function(){
            console.log("Mouse in(Offspring will not trigger)");
        })
        oDiv.addEventListener("mouseleave",function(){
            console.log("Mouse out(Offspring will not trigger)");
        })

    </script>
</body>

Operation results:

5.3 # keyboard related event types

5.3.1} event type

keydown    Keyboard key press
keypress    Keyboard key press
keyup      Keyboard key lift
e.keyCode    Keyboard key number
e.altKey
e.ctrlKey
e.shiftKey                                                                                
It's all about judging whether the button is pressed or not
If pressed, the return value is true
If not pressed, the return value is false

be careful:

The difference between keydown and keypress is that all keys will trigger the keydown event, and some special keys will not trigger the keypress event. For example, esc ctrl alt shift back will not trigger the keypress event

5.3.2} compatibility

Lower versions of Firefox use
e.which stores the key number
Now all browsers use
e.keyCode and e.which store key numbers at the same time

5.3.3 # precautions

1. Keyboard events are only supported by tags that can get focus by default
Generally, it's just input tag and textarea
And document documentElement document. body

2. Tags such as div that cannot obtain focus can bind keyboard events through the throwing of events

3. Keyboard press event. If you keep pressing the keyboard button, the event will be triggered all the time

Demo code:

<body>
    <input type="text">
    <script>
        const oIpt = document.querySelector("input");
        oIpt.addEventListener("keydown",function(){
            console.log("The keyboard is pressed(keydown)");
        })
        oIpt.addEventListener("keypress",function(){
            console.log("The keyboard is pressed(keypress) esc ctrl alt shift back And so on will not trigger keypress event ");
            
        })
        oIpt.addEventListener("keyup",function(){
            console.log("The keyboard is raised");
        })
    </script>
</body>

Operation results:

5.4} related event types of the form

submitThe form submission event is bound to the form tag, and the submission event is triggered when the submit button is clicked to trigger the submission event
focusTag get focus event triggered when tag get focus
blur        Tag out of focus event triggered when tag out of focus
change      When the tag loses focus and the data changes, an event is triggered when the tag loses focus and the data changes
input      Input data} an event is triggered each time data is output

Demo code:

<body>
    <form>
        <input type="text">
        <button>Submit</button>
    </form>
    
    <script>
        const oForm = document.querySelector("form");
        const oIpt = document.querySelector("input");
        oIpt.addEventListener("focus",function(){
            // Event triggered when tag gets focus
            console.log("Get focus");
        })
        oIpt.addEventListener("blur",function(){
            // Event triggered when the tag loses focus
            console.log("Lose focus");
        })
        oIpt.addEventListener("change",function(){
            // Tag loses focus and data changes
            console.log("An event is triggered when the tag loses focus and the data changes");
        })
        oIpt.addEventListener("input",function(){
            // An event is triggered each time data is output
            console.log("You entered the data");
        })
    </script>
</body>

Operation results:

5.5 mobile terminal events

touchstart  Touch start
touchend    Touch end
touchmove  Touch move

Since the blogger's skill is still shallow, I can't explain such events in detail for the time being. Sorry!  

5.6 special events

transitionstart    Transition begins
transitionend      End of transition
animationstart      Animation start
animationend        End of animation

Since the blogger's skill is still shallow, I can't explain such events in detail for the time being. Sorry!  

6, Coordinates in event Click

6.1 , coordinates relative to the upper left corner of the tag object that triggered the event

e.offsetX

e.offsetY

Code demonstration:

    <script>
        const oDiv = document.querySelector("div");
        oDiv.addEventListener("click",function(e){
            // Coordinates relative to the upper left corner of the label object that triggered the event
            console.log(e.offsetX);
            console.log(e.offsetY);
        })
    </script>

Operation results:

 

6.2 coordinates relative to the upper left corner of the window

e.clientX

e.clientY

Code demonstration:

<body>
    <div></div>
    <script>
        const oDiv = document.querySelector("div");
        oDiv.addEventListener("click",function(e){
             // Relative to window
            console.log(e.clientX);
            console.log(e.clientY);
        })
    </script>
</body>

Operation results:

 

 

6.3 coordinates relative to the upper left corner of the HTML page

e.pageX

e.pageY

Code display:

<body>
    <div></div>
    <script>
        const oDiv = document.querySelector("div");
        oDiv.addEventListener("click",function(e){
            // Coordinates relative to the upper left corner of the HTML page
            console.log(e.pageX);
            console.log(e.pageY);
        })
    </script>
</body>

Operation results:

 

7, Event object event

7.1 definition

The data value stored in the parameter in the event handling function is the relevant data information of the object triggering the event

The object that triggers the event and the object that binds the event are not necessarily the same object

When an event is triggered, the JavaScript program automatically stores the argument in the formal parameter, that is, automatically stores the flag of the trigger event in the event object

7.2 syntax

Event source Addeventlistener (event type, function (event object){

Event object target 

})


8, Event delegation

8.1 definition

Instead of directly binding events to the tag object, bind events to the parent tag through the event object target judges different tag objects that trigger events and executes different function programs.

8.2 syntax

Object object target is a DOM tag object

Object object target.tagName is the label name in uppercase English characters

Object object target executes DOM operation to determine what tag is clicked

8.3 advantages

(1) Adding objects to only one tag event and executing different programs through judgment will lead to higher execution efficiency

(2) It is more conducive to add events to the labels generated by dynamic rendering

Therefore, the tag generated by dynamic rendering uses event delegation to add events to the existing parent, and judge the event object through event delegation What tag is target and what program is triggered.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        footer{
            width: 1000px;
            height: 800px;
            background-color: blue;
            margin: auto;
        }
        div{
            width: 800px;
            height: 600px;
            margin: auto;
            background-color: blueviolet;
        }
        h1{
            width: 600px;
            height: 400px;
            margin: auto;
            background-color: red;
        }
        p{
            width: 400px;
            height: 200px;
            margin: auto;
            background-color: pink;
        }
    </style>
</head>
<body>
<footer>
    <div>
        <h1>
            <p></p>
        </h1>
    </div>
</footer>
<script>
    const oFooter = document.querySelector("footer");

    oFooter.addEventListener("click",function(e){
        // Judge the clicked tag object through event delegation and execute the corresponding program
        if(e.target.tagName === "FOOTER"){
            console.log("What you click is footer");
        }else if(e.target.tagName === "DIV"){
            console.log("What you click is div");
        }else if(e.target.tagName === "H1"){
            console.log("What you click is h1");
        }else if(e.target.tagName === "P"){
            console.log("What you click is p");
        }
    })
</script>
</body>
</html>

Operation results:

Keywords: Javascript Front-end JQuery

Added by kingbeastie on Fri, 04 Feb 2022 09:44:56 +0200