JS Basics: Events

1, Event binding method

1.1 inline mode

In the inline model, an event handler is an attribute of an HTML tag that handles a specified event. Although inline was widely used in the early days, it was mixed with HTML and was not separated from HTML.

//In HTML, the event handler function is used as an attribute to execute JS code
<input type="button" value="Button" onclick="alert('Lee');" />//Note the single and double quotation marks
//In HTML, the event handler function is used as an attribute to execute JS functions
<input type="button" value="Button"onclick="box();" />//Functions that execute JS
PS: Function cannot be placed in window.onload Inside, so you can't see.

1.2 outreach mode (script mode)

Because the inline model violates the principle of hierarchical separation of HTML and JavaScript code. To solve this problem, we can handle events in JavaScript. This is the script model.

var input=document.getElementsByTagName('input')[0];//Get input object
input.onclick=function(){//Anonymous function execution
	alert('Lee');
};
PS: The corresponding code can be triggered directly through anonymous functions. The function can also be executed by assigning a value to the specified function name(The assigned function name should not be followed by parentheses). 
input.onclick=box;   //Assign the function name to the event handler

2, Event handler

The types of events that JavaScript can handle are: mouse events, keyboard events, and HTML events
PS: all event handling functions are composed of two parts: on + event name. For example, the event handling function of click event is onclick. Here, we mainly talk about the way of script model to build events. We ignore the inline mode that violates the separation principle.

2.1 mouse event, all elements of the page can be triggered

click: triggered when the user clicks the mouse button or presses the Enter key
dblclick: triggered when the user double clicks the main mouse button.
mousedown: triggered when the user presses the button and the mouse does not pop up.
mouseup: triggered when the user releases the mouse button.
mouseover: triggered when the mouse moves over an element.
mouseout: triggered when the mouse moves over an element.
mousemove: triggered when the mouse pointer moves over an element.
mouseenter: triggered when the mouse moves over an element.
mouseleave: triggered when the mouse moves over an element.
PS: the child nodes of mouseover will trigger repeatedly, but mouseenter will not. Mouseenter will only exist after IE8

2.2 keyboard event, triggered by form element or window

keydown: when the user presses any key on the keyboard, the trigger will be repeated if it is held down.
οnkeydοwn=function(){
alert('Lee');
};
keypress: triggered when the user presses the character key on the keyboard. If you hold it down, it will be triggered repeatedly
οnkeypress= function(){
alert('Lee');
};
keyup: triggered when the user releases the key on the keyboard.
οnkeyup=function() {
alert('Lee');
};

2.3 HTML event, triggered by form element or window

//load: triggered on the window after the page is fully loaded, or on the frameset after the frameset is loaded.
window.onload=function() { alert('Lee'); };
//unload: triggered on the window after the page is completely unloaded, or on the frameset after the frameset is unloaded.
//Only IE browser is compatible. It is triggered when the page is deconstructed (refresh the page or close the current page)
window.onunload= function(){ alert('Lee'); };
//resize: triggered on the window or frame when the size of the window or frame changes. 
window.onresize=function(){ alert('Lee'); };
//Scroll: triggered when the user scrolls an element with a scroll bar.
window.onscroll=function() { alert('Lee'); };
//select: triggered when the user selects one or more characters in the text box (input or textarea).
//Triggered when we select text in the input box (the cursor selects the value in input)
input.onselect=function(){ alert('Lee'); };
//change: triggered when the content of the text box (input or textarea) changes and loses focus.
//Triggered when we modify the text and lose focus
input.onchange=function(){ alert('Lee'); };
//Focus: triggered on the window and related elements when the page or element obtains focus.
input.onfocus= function(){ alert('Lee'); };
//blur: triggered on the window and related elements when the page or element loses focus. 
input.onblur=function(){ alert('Lee'); };
//Submit: triggered on the < form > element when the user clicks the submit type=submit button. Must be a form element
form.onsubmit=function(){ alert('Lee'); };
//Reset: triggered on the < form > element when the user clicks the reset type=reset button. Must be a form element
form.onreset=function(){ alert('Lee'); };

3, Event object

3.1 event object

The event object consists of three parts: object. Event handler = function

//For example, click anywhere in the document.
document.onclick=function(){
	alert('Lee');
};

PS: the noun explanation of the above program: click indicates an event type, click. onclick represents an event handler function or a property of a bound object (or event listener or listener). document represents a bound object used to trigger an element region. function() anonymous function is an executed function, which is used for execution after triggering.

function box() {//Ordinary null parameter function
	alert(arguments.length); //0, did not get any passed parameters
}
input.onclick=function(){//Event bound execution function
	alert(arguments.length); //1. Get a hidden parameter
};
[Note] through the above two groups of functions, we find that the execution function bound by events can get a hidden parameter. 
Note: the browser will automatically assign a parameter, which is actually event Object.
When we click the button, the system will automatically call the event bound function and pass the event object as the first parameter of the function.

input.onclick=function(){
	alert(arguments[0]); //MouseEvent, mouse event object
};//This method is tired, so the simpler method is to get it directly by receiving parameters.
input.onclick=function(evt){
	//Accept the event object. The name does not have to be event
	alert(evt); //MouseEvent, mouse event object
};
//For the compatibility writing method of event object, use window.event under low version ie (IE8).
input.onclick=function(evt){
	var e = evt || window.event;
	alert(); 
};

3.2 event object properties

3.2.1 button attribute

3.2.2 mouse events (visual area and screen coordinates)

Visual area and screen coordinates. The event object provides two groups to obtain the properties of browser coordinates, one is the page visual area coordinates, and the other is the screen coordinates
The upper left corner of the clientX clientY visual window is the origin
screenX screenY the upper left corner of the screen is the origin
pageX pageY the upper left corner of the whole page, including the rolling distance

document.onclick=function(evt) {
    alert(evt.clientX +','+evt.clientY);
    alert(evt.screenX+','+evt.screenY);
};

difference
screenX: the horizontal offset of the mouse position relative to the user's screen, and screenY is the vertical direction. At this time, the reference point, that is, the origin, is the upper left corner of the screen.
clientX: compared with screenX, the reference point is changed to the upper left corner of the browser content area, and the reference point will move with the movement of the scroll bar.
pageX: the reference point is also the upper left corner of the browser content area, but it does not change with the scroll bar.

3.2.3 mouse events (modify keys)

Sometimes, we need some keys on the keyboard to cooperate with the mouse to trigger some special events. These keys are: Shfit, Ctrl, Alt and mean (Windows key in windows and Cmd key in MACS). They are often used to modify mouse events and behaviors, so they are called modify keys.

3.3 keyboard events

3.3.1 keyCode

When keydown and keyup events occur, the keyCode attribute of the event object will contain a code corresponding to a specific key on the keyboard. For alphanumeric character sets, the value of the keyCode attribute is the same as the encoding of the corresponding uppercase letter or number in ASCII code. Case in letters does not affect.

document.onkeydown=function(evt) {
	alert(evt.keyCode); //Press any key to get the corresponding keyCode
};

3.3.2 charCode character coding

The event objects of Firefox, Chrome and Safari all support a charCode attribute. This attribute contains a value only when the keypress event occurs, and this value is the ASCII encoding of the character represented by the key pressed. At this time, the keyCode is usually equal to 0 or may also be equal to the code of the key.

function getCharCode(evt) {
     if(typeof evt.charCode== 'number') {
         return evt.charCode; 
     }else{
         return evt.keyCode;
     }
}
PS: have access to String.fromCharCode()take ASCII The encoding is converted to actual characters.

3.4 element node triggering event (target)

document.onclick=function(evt) {
     alert(evt.target || window.event.srcElement);
};

4, Event bubbling and event capture

4.1 event flow

Event flow describes the sequence of receiving events from the page. When several elements with events are stacked together, you click one of the elements, not only the currently clicked element will trigger the event, but all elements stacked in your click range will trigger the event. Event flow includes two modes: bubbling and capturing.

4.2 event bubbling

It's triggered one by one from the inside out

4.3 event capture

It is triggered one by one from the outside to the inside. So modern browsers are bubble mode by default

4.4 prevent event bubbling

Event bubbling will bring a lot of trouble to our actual development, so we should prevent event bubbling.

//Stop bubbling
cancelBubble=true        stopPropagation()

5, Block right-click menu

document.oncontextmenu = function(){
    alert("Right button pressed");
    return false;
}//Block the official right-click menu

5.1 customize the right-click menu

//Customize right-click menu (HTML)
<body >
<div id="divId" style="width:300px;height:200px;background-color:red">
</div>
<div id="menuDiv" style="position:absolute;width:100px;height:80px;background-color:gray; ">
	<ul >
		<li>Menu 1</li>
		<li>Menu 2</li>
		<li>Menu 3</li>
	</ul>
</div>
</body>

//Customize right-click menu (JS)
document.oncontextmenu=function(){
	return false;
}
document.getElementById("divId").onmousedown=function(){
	if(event.button==2){
		var menuDiv = document.getElementById("menuDiv");
		menuDiv.style.left = event.clientX+"px";
		menuDiv.style.top = event.clientY+"px";
		menuDiv.style.display = "block";
	}
}
document.body.onclick=function(){
	document.getElementById("menuDiv").style.display = "none";
}

6, Block default behavior of hyperlinks

Sometimes you need to add a click event on the a tag and process some transactions before jumping, so you need to do some processing

function test(){
	if(window.confirm("Are you sure you want to go?")){
		return true;
	}else{
		return false;
	}
}
<body >
	<a href="test.html" onclick="test()">go</a>
</body>

Sometimes we need to block the default behavior of events. For example, click the default behavior of a hyperlink and jump to the specified page. Then blocking the default behavior can mask the jump operation and implement the custom operation.
Another nonstandard way to cancel the event default behavior is to return false.

link.onclick = function () {
	alert('Lee'); 
	return false; //Just give a vacation and you won't jump.
};

PS: return false; This function can be realized, but there are loopholes;
First, it must be written at the end, which may lead to return false after the intermediate code is executed;
Second: return false when it is written to the front, the subsequent customization operations will be invalid.
Therefore, the best way is to block the default behavior at the beginning and execute the code later.

7, Drag principle

Drag three swordsmen: related events (onmousedown\onmousemove\onmouseup)
Drag and drop ideas:

  1. Add onmousedown event to the target element. The premise of dragging is to press the left mouse button on the target element
    Record the relative distance between the mouse down position and the target element
  2. After onmousedown occurs, the onmousemove event is added to the document, which means that the mouse movement on the web page will change the position of the target element
    In the onmousemove event, set the left and top formulas of the target element.
    left of target element = clientX of mouse – (abscissa difference between mouse and element, i.e. offsetX)
    top of the target element = clientY of the mouse – (the ordinate difference between the mouse and the element, i.e. offsetY)
  3. When onmousedown occurs, adding an onmouseup event to the document at this moment means that if you release the mouse anywhere on the web page, the drag effect will be abandoned
  4. Get the width and height of the browser:
    windowWidth = document.documentElement.clientWidth || document.body.clientWidth

8, Event listener

8.1 add event listener

Event listener: the addEventListener() method is used to add an event handle to the specified element. IE8 and below are not supported, and Firefox and Google support it.

Event listener target.addEventListener("click", fun, false)

  1. "click": is the event name; Note that the on of the event name should be removed
  2. fun: is the function name; Note that there are no double quotes on the function name
  3. The third parameter is whether to use capture (reverse bubbling). The default is false and bubbling.

Multiple functions can be bound on an object, and the execution order is determined according to the binding order

document.getElementById("myBtn1").addEventListener("click",myfun1,false);

When the bound function has parameters and the parameter value is passed, use "anonymous function" to call the function with parameters:

document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1, p2);
});

8.2 removing event listeners

The removeEventListener() method removes the event function added by the addEventListener() method:

document.getElementById("myBtn1").removeEventListener("click",myfun1);

(1) If you repeatedly add a click event to a button, it will be overwritten, and the event listener will not be overwritten. Moreover, if you write 100 lines of code after clicking the event, you want to continue to add functions to the button event, you can directly add an event listener without finding the function position corresponding to the button (because the event listener will not be overwritten, it can be executed).
(2) If there are multiple functions on an event, to delete the function of an event, the traditional event binding will only set the event from the original function to null, and the original click event on the button will also be set to null. Using the event listener, you can remove functions for a specified event.
(3) Event capture: trigger from outside to inside, event bubble: start from inside to outside

1,Traditional event binding
	<1>Repeat add, overwrite
	<2>A function on an event cannot be deleted precisely
2,Event listener (lower version) IE (incompatible under Browser)
	addEventListener()
		Format: node.addEventListener("click")
		Parameters:
			 First parameter event type
			 Second parameter binding function
			 Third parameter Boolean  true  Event capture
					     		 false Event bubble default
	removeEventListener()
		Format: node.removeEventListener
		Parameters:
			First parameter event type
			The second parameter deletes the function name

8.3 event listener compatibility

IE implements two methods similar to those in DOM: attachEvent() and detachEvent(). Both methods accept the same parameters: event name and function

//Add events across browsers
function addEvent(obj, type, fn) {//btn,click,show
	if (obj.addEventListener) {
		obj.addEventListener(type, fn, false);
	} else if (obj.attachEvent) {
		obj.attachEvent('on' + type, fn);
	}
}
//Remove events across browsers
function removeEvent(obj, type, fn) {
	if (obj.removeEventListener) {
		obj.removeEventListener(type, fn, false);
	} else if (obj.detachEvent) {
		obj.detachEvent('on' + type, fn);
	}
}

9, Event delegation

onclick, onmouseover, onmouseout, etc. are events. Delegation is to let others do it. This event was originally added to some elements, but you added it to others to do it and complete the event.
That is: using the bubble principle, add the event to the parent to trigger the execution effect.

Rule of the strongest king of event entrustment:

  1. Find the parent or grandfather node of the element node to which you want to add the event
  2. Label that binds the event to the parent
  3. Find out the object (target, not this) that triggers the event and judge
var oUl = document.getElementById("ul1");
	oUl.onclick = function(ev){
		var e = ev || window.event;
		var target = e.target || window.event.srcElement;
		if(target.nodeName.toLowerCase() == "li"){
			target.style.backgroundColor = 'red';
		}
	}
	var obtn = document.getElementById("btn1");
	var i = 6;
	obtn.onclick = function(){
		var newNode = document.createElement("li");
		newNode.innerHTML = i++ * 1111;
		oUl.appendChild(newNode);
}

Keywords: Javascript Front-end ECMAScript

Added by raptoni on Mon, 08 Nov 2021 16:24:16 +0200