How to prevent event propagation in the front end
This time I will show you how to prevent event propagation in the front end, and what are the precautions to prevent event propagation in the front end. The following is a practical case, let's take a look.
Make a small demo, click the button to display the floating layer, click elsewhere to close the floating layer, and write a simple css
<style> .wrapper{ position:relative; display:inline-block; } .popover{ position:absolute; border:1px solid red; left:100%; top:0; padding:10px; margin-left:10px; background:white; display: none; /*默认隐藏*/ } .popover::before{ position:absolute; content:''; top:5px; right:100%; border:10px solid transparent; border-right-color:red; } .popover::after{ position:absolute; content:''; top:5px; right:100%; border:10px solid transparent; border-right-color:white; margin-right:-1px; } </style> <p id="wrapper" class='wrapper'> <button id="clickMe">点我</button> <p id="popover" class="popover"> <input type="checkbox">浮层 </p> </p> <script> clickMe.addEventListener('click',function(){ popover.style.display = 'block'; }); </script>
Now what if I click on a blank space on the page to close it? What method should be used? It is easy to think of monitoring documents, such as the following code
document.addEventListener('click',function(){ popover.stely.display = 'none'; });
. However, after actually writing it like this, the buttons are invalid and there is no response no matter how you click them. Why is this?
After understanding the capture and bubbling events mentioned in the previous article, you can easily understand this point, you can []().
We did not specify whether the monitoring is in the capturing or bubbling phase. The browser defaults to the bubbling phase. When we click the button, the capturing phase does not happen, but the bubbling phase is different. First button
The upper function is triggered first, and then the document
upper function is also triggered, causing the floating layer to appear to be hidden again.
Then you may want to ask, has the event on button
been executed? In fact, both events are executed, but the time is too short. The browser executes them together by default. You can add a debugger
inside and you can see it.
clickMe.addEventListener('click',function(){ popover.style.display = 'block'; });
So how to solve it? The simplest way is to, in addition to executing popover.style.display = 'block'
, also prevent the event from propagating
clickMe.addEventlistener('click',function(){ popover.style.display = 'block'; }); popover.addEventListener('click',function(e){ e.stopPropagation(); });
Why is it added to the parent element of the button here? If it is not added on the parent element, the floating layer will be closed when you click it.
If there are many listeners on the page, this method is a waste of memory. A more memory-saving method is to use JQuery
$(clickMe).on('click',function(){ $(popover).show(); $(document).one('click',function(){ $(popover).hide(); }); }); $(wrapper).on('click',function(e){ e.stopPropagation(); })
Do not listen at the beginning, only after popover
Listen once during `show` and turn it off immediately. This is called cleaning up the battlefield. $(wrapper).on('click',false)
is completely equivalent to the following code
$(wrapper).on('click',function(e){ e.preventDefault(); //阻止默认事件 e.stopPropagation(); //阻止传播 })
But if there is a checkbox
in the page, you If the organization default event is added to any layer of its parent element, including checkbox
itself, then this checkbox
cannot be check
.
There is a question here. If the propagation of the event is not prevented, what will happen as shown below?
$(clickMe).on('click',function(){ $(popover).show(); $(document).one('click',funtion(){ $(popover).hide(); }); });
Of course, as before, nothing will happen, so what happened when I clicked the button?
When I click the button, it will do two things. First, popover
`show will come out, and then the
hide function will be added to
documentAbove, when the event propagates to
document`, it will be hidden again.
You can add a setTimeout()
function to it to solve this problem
$(clickMe).on('click',function(){ $(popover).show(); setTimeout(function(){ $(document).one('click',function(){ $(popover).hide(); }) },0) });
setTimeout(fn,0)
This0
It is not executed immediately, but executed as soon as possible. Specifically, the function here is executed after the bubbling ends. In other words, when the bubbling ends, the listening event is added to document
and waits for the user Click to execute next time.
Summary:
Monitoring
button
anddocument
at the same time, nothing happens when you click on it, because both functions are executed Well, the problem is solved by preventing event propagation, which is a waste of memory.The best way is to use jQuery, and listen to
document## after clicking the
button#, if it is closed, it will no longer listen, and it will not prevent the propagation of events, and nothing will happen when you click on it. There are two solutions: one is to prevent the propagation of events, and the other is to add a
setTimeout()function.
React-router v4 usage steps detailed explanation
Chart.js lightweight chart library use case Analysis
Chart.js lightweight HTML5 chart drawing tool library detailed steps to use
The above is the detailed content of How to prevent event propagation in the front end. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics


![Event ID 4660: Object deleted [Fix]](https://img.php.cn/upload/article/000/887/227/168834320512143.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

On iPhones running iOS 16 or later, you can display upcoming calendar events directly on the lock screen. Read on to find out how it's done. Thanks to watch face complications, many Apple Watch users are used to being able to glance at their wrist to see the next upcoming calendar event. With the advent of iOS16 and lock screen widgets, you can view the same calendar event information directly on your iPhone without even unlocking the device. The Calendar Lock Screen widget comes in two flavors, allowing you to track the time of the next upcoming event, or use a larger widget that displays event names and their times. To start adding widgets, unlock your iPhone using Face ID or Touch ID, press and hold

Sometimes, we want to block certain websites on Microsoft Edge for many reasons, whether it is for parental control, time management, content filtering, or even security concerns. A common motivation is to be more productive and stay focused. By blocking distracting websites, people can create a conducive environment for working or studying, minimizing potential distractions. Finally, content filtering is important to maintaining a safe and respectful online environment. Blocking websites that contain explicit, offensive or objectionable content is particularly important in educational or professional settings where upholding appropriate standards and values is crucial. If you can relate to this situation, this article is for you. Here’s how to block access to the Internet in Edge

When a value is added to the input box, the oninput event occurs. You can try running the following code to understand how to implement oninput events in JavaScript - Example<!DOCTYPEhtml><html> <body> <p>Writebelow:</p> <inputtype="text"

jQuery is a popular JavaScript library that can be used to simplify DOM manipulation, event handling, animation effects, etc. In web development, we often encounter situations where we need to change event binding on select elements. This article will introduce how to use jQuery to bind select element change events, and provide specific code examples. First, we need to create a dropdown menu with options using labels:

Commonly used events in jquery are: 1. Window events; 2. Mouse events, which are events generated when the user moves or clicks the mouse on the document, including mouse clicks, move-in events, move-out events, etc.; 3. Keyboard events, Events are generated every time the user presses or releases a key on the keyboard, including key press events, key release events, etc.; 4. Form events, such as the focus() event will be triggered when an element gains focus, and the focus() event will be triggered when it loses focus. The blur() event is triggered, and the submit() event is triggered when the form is submitted.

How to prevent memory leaks in closures? Closure is one of the most powerful features in JavaScript, which enables nesting of functions and encapsulation of data. However, closures are also prone to memory leaks, especially when dealing with asynchronous and timers. This article explains how to prevent memory leaks in closures and provides specific code examples. Memory leaks usually occur when an object is no longer needed but the memory it occupies cannot be released for some reason. In a closure, when a function refers to external variables, and these variables

How to implement calendar functions and event reminders in PHP projects? Calendar functionality and event reminders are one of the common requirements when developing web applications. Whether it is personal schedule management, team collaboration, or online event scheduling, the calendar function can provide convenient time management and transaction arrangement. Implementing calendar functions and event reminders in PHP projects can be completed through the following steps. Database design First, you need to design a database table to store information about calendar events. A simple design could contain the following fields: id: unique to the event
