Detailed Explanation of Native JS Events

Keywords: Attribute Javascript IE Windows

What is an event?

The action of the browser page through the mouse and keyboard is the event.
Once an event occurs, it requires event handling, which is called event-driven, and event-driven is usually performed by functions.
onclick: mouse click
onmouseover: Mouse in
onmouseout: Mouse out
onkeyup: Keyboard press and lift
onkeydown: press the keyboard
onchange: content change
onblur: losing focus
onfocus: get focus
onsubmit: Form submission

Set events

1) Mainstream browser mode (including IE9 version browser):
Itnode.addEventListener (event type, event processing [, event flow]); //settings
Itnode.removeEventListener (event type, event handling [, event flow]); //Cancel

2) IE browser mode (IE6/7/8):
Itnode. attachEvent (event type, event handling);//Settings
Itnode.detachEvent (event type, event handling);//Cancel

Event types: Specific events that we can set up, such as onclick/onmouseover, etc.
There is no "on flag" in the mainstream browser mode, such as addEventListener('click',... );
IE browser mode has "on" flag, such as attachEvent('onclick')

Event handling: Event-driven, which can be an anonymous/anonymous function
For example, addEventListener('click', function() {}/ named function);

Event streams: true capture, [false bubble]

Specific requirements for removeEventListener/detachEvent operations:
Event handling must be a named function, not an anonymous function.
(2) The parameters of event cancellation are exactly the same as those of binding (quantity/content)

Characteristic:
(1) Multiple events of the same type can be set for the same object.
(2) Event cancellation is also very flexible.
(3) Event flow is also well handled and controlled.

<h2>Event setup</h2>
<script>
//Appended event
    var dv=document.getElementsByTagName('h2')[0];
    dv.addEventListener('click',function(){
        //Event Processing
        dv.style.backgroundColor='lightblue';
    });
    dv.addEventListener('click',over);
    function over(){
        console.log("Click event triggered");
    }
//Event cancellation
    dv.removeEventListener('click',over); //The original action is no longer triggered
</script>

The rendering (the following address is a watermarking): ___________

Event stream

Multiple nested elements have the same event. When the most internal element event is triggered, the same type event of the outer element will also be triggered. The effect of simultaneous execution of multiple elements with the same type of event is called "event flow".
Illustration:

Event flows fall into two types:
Bubble: Events are executed from the inside to the outside. false
Capture: Events are executed sequentially from the outside to the inside. ture
// addEventListener (type, processing, event flow true capture /[false bubbles]);

<h2>Event Flow Effect</h2>
<div>
    <p>
        <span>Today is very good</span>
    </p>
</div>
<script>
var dv=document.getElementsByTagName('div')[0];
var p=document.getElementsByTagName('p')[0];
var sp=document.getElementsByTagName('span')[0];
dv.addEventListener('click',function(){
    console.log('I am div');
},true);
p.addEventListener('click',function(){
    console.log('I am p');
},true);
sp.addEventListener('click',function(){
    console.log('I am sp');
},true);
</script>

Design sketch:

If the third parameter after the above code is not true, the default or false result is as follows:

Event object

Event objects, each event (including mouse, keyboard events) trigger the execution process, there are corresponding event objects, through the event object can get the coordinate information of the mouse relative to the page, through the event object can also perceive what keys are triggered to execute, through the event object can also prevent the flow of events, prevent the default action of browsers.

Get event objects

Mainstream browser (IE9 version browser):
The first parameter of the event handler is the event object.
For example:
node.onclick = function(evt){evt is the event object}
AddEventListener (type, function(evt) {}/ function name);
Function function name (evt) {}
// evt is the event object

(2) IE(6/7/8) browser
node.onclick = function(){window.event event object}
// Event, the global variable, is the event object.

The direct superior object of the global variable is window. Global variable information can be accessed through windows.
window.document.getElementById();

Event Object Role

1) Get coordinate information of mouse
event.clientX/clientY;//relative dom region coordinates
event.pageX/pageY; //relative dom region coordinates, considering scrollbar distance
event.screenX/screenY;//relative screen coordinates

<div>Today is very good</div>
<script>
var dv=document.getElementsByTagName('div')[0];
dv.onclick=function(evt){
    //Regional coordinates relative to dom
    console.log(evt.clientX+"---"+evt.clientY);
    //Compute the scroll bar relative to the dom area coordinates
    console.log(evt.pageX+"---"+evt.pageY);
    //Relative to screen coordinates
    console.log(evt.screenX+"---"+evt.screenY);
}
</script>

Blocking the flow of events

event.stopPropagation(); //mainstream browser window. event. cancelBubble = true; //IE (678) browser
Bubble type, capture type can be prevented, in order to prevent more meaningful, only consider the bubbles can be.

<h2>Event Flow Effect</h2>
<div>
    <p>
        <span>Today is very good</span>
    </p>
</div>
<script>
var dv=document.getElementsByTagName('div')[0];
var p=document.getElementsByTagName('p')[0];
var sp=document.getElementsByTagName('span')[0];
dv.addEventListener('click',function(evt){
    console.log('I am div');
    evt.stopPropagation();   //Blocking the flow of events
});
p.addEventListener('click',function(){
    console.log('I am p');
    evt.stopPropagation();   //Blocking the flow of events
});
sp.addEventListener('click',function(){
    console.log('I am sp');
    evt.stopPropagation();   //Blocking the flow of events
});
</script>

Design sketch:

Perception of triggered keyboard keypad information

event.keyCode obtains keycode information corresponding to the keyboard
The keyCode numeric code information obtained by event triggering can correspond to the keyboard key information.

<h2>Event Object Role</h2>
<input type="text" id="username">
<script>
//Perception of triggered key sub-information
var it = document.getElementById('username');
it.addEventListener('keydown',function(evt){
    //alert(evt);  //[object KeyboardEvent]
 var num=evt.keyCode;  //Get the "numeric code" of the triggered keys
    console.log(num);
});
</script>

Prevent Browser Default Actions

Browser default action, registration form page, when submitting the form, the browser's page will jump according to the action attribute value, this action is called "browser default action".

Form form submission requires validation of various form fields, and browser jumps are prohibited if validation fails.

event.preventDefault(); // mainstream browsers (both dom1 and dom2 level events work)
Event. returnValue = false; //IE (678) browser
Return false; //dom1 level event settings work

<form method='post' action='./1.php'>
    //Password:<input type="password" name="pwd"><br />
    <input type="submit" value="register">
</form>
<script>
var fm=document.getElementsByTagName('form')[0];
fm.addEventListener('submit',function(evt){
    alert('Incorrect password!');
    evt.preventDefault();
});
</script>

Load event onload

When js code is executed, it needs the support of html & css, so that html code is executed first (first in memory) and js code is executed later.
The final execution process of js code is "loading process", which is usually implemented by "loading event"

Loading event onload ensures that js code is executed at HTML & css, and that it is executed at the end.
Specific settings:

<body onload="load function ()">
window.onload = anonymous/named function; //recommendation

Remarks

If you use dom1 level operation, you should pay attention to the following two points:

<h2 id='h'>today is good</h2>
<script>
    var obj=document.getElementById("h");
    function f1(){
        console.log("The event was triggered.!");
    }
    //Here the function-passing address writes the function name without parentheses
    h.onclick=f1;   
</script>
<!--Here the function passes address with parentheses and Quotes-->
<h2 id='h' onclick="f1()">today is good</h2>
<script>
    var obj=document.getElementById("h");
    function f1(){
        console.log("The event was triggered.!");
    } 
</script>

Posted by nicandre on Thu, 21 Mar 2019 13:54:51 -0700