JavaScript--Advanced Application of Event Processing

1. What is an event

Refers to an action or response that is triggered under certain conditions. An event can be an action caused when a user interacts with a web page, such as clicking a button, submitting a form, mouse movement, etc., or it can be an action triggered by a browser or other code, such as page loading completion, time arrival, etc.

We can respond to various events by adding event handlers. An event handler is a piece of JavaScript code that defines an action to be performed when an event occurs. By binding event handlers to specific HTML elements, when the event is triggered, the corresponding code will be executed.

Event-driven programming is a common programming paradigm, especially important in web development. It allows us to react instantly to user actions, providing an interactive and dynamic experience.

Here's a simple example that demonstrates how to add a click event handler to a button using JavaScript:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<button id="myButton">点击我</button>
		<script>
			// 获取按钮元素
			var button = document.getElementById("myButton");
			
			// 添加点击事件处理程序
			button.addEventListener("click", function(){
			  alert("按钮被点击了!");
			});

		</script>
	</body>
</html>

The above code will pop up a prompt box when the button is clicked, displaying "The button was clicked!". 

2. Three elements of an event

  1. Trigger (Event Trigger): A trigger is a cause or condition that causes an event to occur. It can be the user's interactive operation, such as clicking a button, mouse movement, etc., or it can be the execution result of other codes, such as the completion of page loading, the arrival of a timer, etc. Triggers define when an event occurs.

  2. Listener (Event Listener): A listener is an object or function responsible for listening to whether a specific event occurs. It will be registered on an element or globally, waiting for a trigger signal. When the event is triggered, the listener will receive the notification and perform the corresponding action. An event can have multiple listeners.

  3. Event Handler: A handler is a code block or function that is executed after a listener receives an event. It defines actions to be performed when an event occurs, such as updating page content, sending network requests, validating forms, etc. The handler is the part that actually responds to the event.

These three elements together form a complete event model. Triggers fire events, listeners receive and deliver events, and handlers execute responses to events. Through the event model, we can realize the interactive function of the web page and obtain a better user experience. 

3. Types of events

  1. mouse events:

    • click: This event is triggered when the mouse is clicked.
    • dblclick: This event is triggered when the mouse is double-clicked.
    • mousedown: This event is fired when the mouse button is pressed.
    • mouseup: This event is fired when the mouse button is released.
    • mousemove: This event is triggered when the mouse pointer moves.
    • mouseover: This event is triggered when the mouse pointer moves over the element (the bubbling cannot be prevented).
    • mouseout: This event is triggered when the mouse pointer moves out of the element (the bubbling cannot be prevented).
    • mouseenter: This event is triggered when the mouse pointer moves over the element (can prevent bubbling).
    • mouseleave: This event is triggered when the mouse pointer moves out of the element (it can prevent bubbling).
    • mousewheel: This event is triggered when the mouse wheel is turned.
    • scroll: This event is fired when the element's scroll bar is scrolled.
  2. Keyboard events:

    • keydown: keyboard press event.
    • keyup: keyboard release event.
    • keypress: The key is pressed and released event.
  3. Form events:

    • blur: This event is fired when the element loses focus.
    • focus: This event fires when the element gets focus.
    • change: This event is fired when the element's value changes.
    • input: This event fires when the element gets user input.
    • invalid: This event is fired when the value of the element is invalid.
    • select: This event is fired when the user selects the content of the element.
    • submit: This event is fired when the form is submitted.
  4. window events:

    • load: Triggered when the page is loaded, it can be used to perform initialization operations or load resources.
    • unload: page leave (close or refresh) event.
    • blur: Triggered when the window loses focus.
    • focus: Triggered when the window gets focus.
    • resize: Triggered when the window size is resized, which can be used to respond to changes in page layout.
    • scroll: Triggered when the window is scrolled, it can be used to implement functions such as scroll monitoring or dynamic loading of content.
    • storage: Run the script when the Web Storage zone is updated (when data in the storage space changes).
  5. Touch events:

    • touchstart: Triggered when a finger touches an element on the screen.
    • touchmove: Triggered when the finger slides on the screen, it will be triggered multiple times in a row.
    • touchend: Triggered when the finger leaves the screen.
    • touchcancel: Triggered when a touch event is canceled, such as a touch ending due to a system event such as a phone call.
  6. Network events:

    • load: Triggered when the page or resource is loaded, for example, the <img> element is loaded, the entire page is loaded, etc.
    • error: Triggered when the page or resource is loaded incorrectly, indicating that the loading failed.
    • unload: Triggered when the page is unloaded or closed, it can be used to perform some cleanup operations.
    • readystatechange: Triggered when the request state of the XMLHttpRequest object changes, used to detect the progress and state of the request.
    • online: Triggered when the device is online, indicating that the network connection is restored.
    • offline: Triggered when the device is offline, indicating that the network connection is lost.
    • beforeunload: Triggered before the page is about to close or leave, it can be used to display a confirmation dialog to the user, prompting whether to leave the page.
  7. Media Events:

    • onabort: Run the script when an abort event occurs.
    • oncanplay: Runs the script when the media is able to start playing, but may need to stop due to buffering.
    • oncanplaythrough: Runs the script when the media is able to play to the end without stopping due to buffering.
    • ondurationchange: Run the script when the media length changes.
    • onemptied: Run the script when the media resource element is suddenly empty (network error, loading error, etc.).
    • onended: Run the script when the media has reached the end.
    • onerror: Run the script when an error occurs during element loading.
    • onloadeddata: Run the script when media data is loaded.
    • onloadedmetadata: Runs the script when the duration of the media element and other media data has been loaded.
    • onloadstart: Run the script when the browser starts loading media data.
    • onpause: Run the script when media data is paused.
    • onplay: Run the script when the media data is about to start playing.
    • onplaying: Run the script when the media data has started playing.
    • onprogress: Run the script when the browser is fetching media data.
    • onratechange: Run the script when the playback rate of the media data changes.
    • onreadystatechange: Run the script when the ready-state changes.
    • onseeked: Run the script when the media element's seek property is no longer true and the seek has ended.
    • onseeking: Run the script when the media element's seek attribute is true and seek has started.
    • onstalled: Run the script when there is an error during (delayed) retrieval of media data.
    • onsuspend: Runs a script when the browser has been fetching media data but stopped before fetching the entire media file.
    • ontimeupdate: Run the script when the media changes its playback position.
    • onvolumechange: Run the script when the media changes volume or when the volume is muted.
    • onwaiting: Run the script when the media has stopped playing but is about to continue playing.
  8. Drag event:

    • ondragstart: Triggered when the element is started to be dragged.
    • ondrag: Triggered continuously during the dragging process, indicating that the position of the dragged element is changing.
    • ondraenter: Triggered when a draggable element enters the bounds of the target element.
    • ondragover: Fires continuously when the dragged element hovers over the target element.
    • ondragleave: Triggered when a draggable element leaves the bounds of the target element.
    • ondrop: Triggered when the dragged element is released, indicating that the dragged element has been placed inside the target element.
    • ondragend: Triggered when the drag operation ends (regardless of whether it was successfully dropped).

      9. Other events:

              1.ontoggle: triggered when the user opens or closes the <details> element.

Sample code for the ontoggle event:

<details ontoggle="handleToggle(event)">
  <summary>点击此处展开/收起内容</summary>
  <p>这是可折叠的内容。</p>
</details>

<script>
function handleToggle(event) {
  if (event.target.open) {
    console.log("内容已展开");
  } else {
    console.log("内容已收起");
  }
}
</script>

Sample code: 

<!DOCTYPE html>
<html>
<head>
  <title>事件示例</title>
  <style>
    .box {
      width: 200px;
      height: 200px;
      background-color: #ccc;
      margin-bottom: 10px;
    }
    .box:hover {
      background-color: yellow;
    }
  </style>
  <script>
    function handleClick() {
      alert("点击事件触发");
    }

    function handleMouseOver() {
      alert("鼠标移入事件触发");
    }

    function handleMouseOut() {
      alert("鼠标移出事件触发");
    }

    function handleKeyDown(event) {
      if (event.key === "Enter") {
        alert("按下回车键");
      }
    }

    function handleFormSubmit(event) {
      event.preventDefault(); // 阻止表单提交的默认行为
      var input = document.getElementById("nameInput");
      alert("输入的姓名是:" + input.value);
    }
  </script>
</head>
<body>
  <div class="box" onclick="handleClick()" onmouseover="handleMouseOver()" onmouseout="handleMouseOut()"></div>

  <input type="text" onkeydown="handleKeyDown(event)">
  
  <form onsubmit="handleFormSubmit(event)">
    <label for="nameInput">姓名:</label>
    <input type="text" id="nameInput">
    <button type="submit">提交</button>
  </form>
</body>
</html>

In the example above:

  • <div>The element has a click event ( onclick), a mouse-in event ( onmouseover), and a mouse-out event ( onmouseout). When the element is clicked, moved in, and moved out, the corresponding event processing function will be triggered, and the corresponding prompt box will pop up.
  • Pressing the Enter key in the text input box will trigger handleKeyDownthe function, and if the Enter key is pressed, a prompt box will pop up.
  • Clicking the submit button or pressing the Enter key in the form will trigger handleFormSubmitthe function, preventing the default submit behavior of the form, and popping up a prompt box to display the entered name.

Expand knowledge:

When the event response function is triggered, the browser will pass an event object as a parameter to the response function. The event object contains information and properties related to the event.

In modern browsers (except IE8 and earlier versions), the event object can be obtained directly through function parameters, for example:

element.addEventListener('click', function(event) {
    // 使用 event 对象进行操作
});

However, in IE8 and earlier browsers, the event object exists as the global variable window.event. In order to be compatible with the old version of IE browser, you can use the following code:

element.attachEvent('onclick', function() {
    var event = window.event;
    // 使用 event 对象进行操作
});

In the above code, by assigning window.event to the local variable event, the code can use the event object normally under different browsers.
Taken together, the compatibility of event objects can usually be handled in the following ways:

element.addEventListener('click', function(event) {
    event = event || window.event; // 兼容IE8及更早版本的浏览器
    // 使用 event 对象进行操作
});

In this way, whether it is a modern browser or a browser of IE8 and earlier versions, it can correctly obtain the event object and perform corresponding operations. 

4. Event flow model

The figure below shows the process of event capture and event bubbling.

The figure below shows the flow of DOM event flow.

  1. Bubbling event flow: The most specific element starts to receive events and propagates up to the outermost element.
  2. Capture event flow: Events are received by the least specific element and propagated down to the most specific element.
  3. DOM event flow: It includes three stages: event capture, target stage, and event bubbling. Events are received from the outermost element, passed through the target element in turn, and finally returned to the outermost element. (event capture → target stage → event bubbling)

Code example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<style>
			div,
			ul,
			li {
				width: 100px;
				height: 50px;
			}

			div {
				background-color: green;
			}

			ul {
				background-color: red;
			}

			li {
				background-color: yellow;
			}
		</style>
	</head>
	<body>
		<div>
			帅哥
			<ul>
				帅哥
				<li>
					帅哥
					<button>
						帅哥
					</button>
				</li>
			</ul>
		</div>
	</body>
	<script>
		//button
		var button_ = document.getElementsByTagName('button')[0];

		button_.addEventListener('click', function() {
			console.log('4');
		}, false)
		//li
		var li_ = document.getElementsByTagName('li')[0];

		li_.addEventListener('click', function() {
			console.log('3');
		}, true)
		//ul
		var ul_ = document.getElementsByTagName('ul')[0];

		ul_.addEventListener('click', function() {
			console.log('2');
		}, false)
		//div
		var div_ = document.getElementsByTagName('div')[0];

		div_.addEventListener('click', function() {
			console.log('1');
		}, true)
	</script>
</html>

When buttons, li elements, ul elements and div elements are clicked, the corresponding event listeners fire and print different numbers in the console:

  • When the button is clicked, the console prints out the number 4.
  • When the li element is clicked, the console will print out the number 3.
  • When the ul element is clicked, the console prints out the number 2.
  • When the div element is clicked, the console will print out the number 1.

Note: In the addEventListener method, the last parameter is a Boolean value, which specifies whether the event is processed during the capture phase. When set to true, it means that the event is processed in the capture phase; when it is set to false, it means that the event is processed in the bubbling phase.

So after clicking the button it will output:

  

5. Event object parameters 

1. Overview: After an event is triggered, an event object will be generated, which contains information related to the event. This event object will be passed to the event processing function as a parameter, so the event processing function will have an event object parameter by default. To use this event object, just define a formal parameter in the event processing function.

2.

When the mouse triggers an event (such as onclick, onmouseover), you can use the following properties to get related information:

  • target: get the element that triggered the event.
  • srcElement: get the event source object
  • type: get event type
  • currentTarget: Gets the element currently processing the event (may be different from target when the event is bubbling).
  • clientX, clientY: Get the horizontal and vertical coordinates of the current mouse on the webpage, only related to the visible area of ​​the webpage
  • pageX, pageY: Get the mouse position relative to the entire page.
  • offsetX, offsetY: Get the mouse position relative to the event source element.
  • screenX, screenY: Get the abscissa and ordinate of the current mouse on the current display
  • dragX: represents the horizontal position of the drag operation, usually representing the horizontal position of the element relative to a reference point (such as the upper left corner of the document).
  • dragY: Represents the vertical position of the drag operation, usually indicating the vertical position of the element relative to a certain reference point.
  • button: Get which key the mouse clicks

When an event is triggered by the keyboard, the following properties can be used to obtain relevant information:

  • keyCode: Get the character code corresponding to the pressed keyboard key.

  • shiftKey, ctrlKey, altKey, metaKey: Determine whether the Shift, Ctrl, Alt, and Meta (Windows key or Command key) keys are pressed at the same time .

In addition, there are some common methods for event handling:

  • preventDefault(): prevent the default behavior of the event.
  • stopPropagation(): Stop the further propagation of the event and prevent the event from bubbling.

Code example:

<!DOCTYPE html>
<html>
<head>
    <title>获取鼠标和键盘事件信息示例</title>
    <script>
        function handleClick(event) {
            var target = event.target;
            var currentTarget = event.currentTarget;
            var clientX = event.clientX;
            var clientY = event.clientY;
            var pageX = event.pageX;
            var pageY = event.pageY;
            var offsetX = event.offsetX;
            var offsetY = event.offsetY;
            var keyCode = event.keyCode;
            var shiftKey = event.shiftKey;
            var ctrlKey = event.ctrlKey;
            var altKey = event.altKey;
            
            console.log('target:', target);
            console.log('currentTarget:', currentTarget);
            console.log('clientX:', clientX);
            console.log('clientY:', clientY);
            console.log('pageX:', pageX);
            console.log('pageY:', pageY);
            console.log('offsetX:', offsetX);
            console.log('offsetY:', offsetY);
            console.log('keyCode:', keyCode);
            console.log('shiftKey:', shiftKey);
            console.log('ctrlKey:', ctrlKey);
            console.log('altKey:', altKey);
        }
    </script>
</head>
<body>
    <button onclick="handleClick(event)">点击我</button>
</body>
</html>

In the above example, when the user clicks the "click me" button, it will be handled by the handleClick function, which receives an event parameter, and obtains information about mouse and keyboard events by accessing the properties of the event object. The debug output will show relevant information.

Let's use the event object parameters to write an interesting html page

<!DOCTYPE html>
<html>
<head>
  <style>
    /* 设置可拖拽元素的样式 */
    .draggable {
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      cursor: move;
    }
  </style>
</head>
<body>
  <!-- 可拖拽的元素 -->
  <div class="draggable">Drag me!</div>

  <script>
    function enableDragging(element) {
      var dragging = false;
      var dragX, dragY;

      // 当鼠标按下时开始拖拽
      document.addEventListener('mousedown', function(e) {
        dragging = true;
        dragX = e.clientX - element.offsetLeft;
        dragY = e.clientY - element.offsetTop;
      });

      // 当鼠标移动时,如果正在拖拽,则更新元素的位置
      document.addEventListener('mousemove', function(e) {
        if (dragging) {
          element.style.left = (e.clientX - dragX) + 'px';
          element.style.top = (e.clientY - dragY) + 'px';
        }
      });

      // 当鼠标释放时结束拖拽
      document.addEventListener('mouseup', function() {
        dragging = false;
      });
    }

    // 获取可拖拽元素并启用拖拽功能
    var draggableElement = document.querySelector('.draggable');
    enableDragging(draggableElement);
  </script>
</body>
</html>

In the above code, a draggable div element is created and the .draggable class is added to it. CSS styles set its width, height, background color, and positioning properties.
The JavaScript part defines the enableDragging function, which registers mousedown, mousemove and mouseup event listeners to achieve dragging effects.

When the mouse is pressed (mousedown event), start dragging:

1. Set the dragging flag to true.
2. Calculate the offset between the mouse position and the upper left corner of the element (dragX and dragY), so that the element position can be updated correctly during the dragging process.
When the mouse moves (mousemove event), if it is in the dragging state, update the left margin and the upper margin of the element according to the position of the mouse, so as to realize the dragging effect.

When the mouse is released (mouseup event), the dragging flag is set to false and the dragging ends.

Finally, select the .draggable class through the querySelector method, get the draggable elements, and call the enableDragging function to enable the dragging function.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/131715389