Home Web Front-end JS Tutorial Js bubbling event prevention code_javascript skills

Js bubbling event prevention code_javascript skills

May 16, 2016 pm 05:42 PM
Event bubbling bubbling event

1. Event target

Now, the variable event in the event handler holds the event object. The event.target attribute stores the target element where the event occurred. This attribute is specified in the DOM API, but is not implemented by all browsers. jQuery makes the necessary extensions to this event object so that this property can be used in any browser. With .target, you can determine the element in the DOM that first received the event (i.e. the element that was actually clicked). Moreover, we know that this refers to the DOM element that handles the event, so we can write the following code:

Copy code The code is as follows:

$(document).ready(function(){
$('#switcher').click(function(event){
$('#switcher .button'). toggleClass('hidden');
})
})

$(document).ready(function(){
$('#switcher').click(function(event ){
if(event.target==this){
$('#switcher .button').toggleClass('hidden');
}
})
})

The code at this time ensures that the clicked element is
and not other descendant elements. Clicking the button now no longer collapses the style converter, while clicking the border triggers the collapse action. However, clicking on the label also does nothing because it is also a descendant element. In fact, we can achieve the goal by not putting the checking code here, but by modifying the button's behavior.

2. Stop event propagation

The event object also provides a .stopPropagation() method, which can completely prevent the event from bubbling. Like .target, this method is a pure JavaScript feature, but cannot be used safely in a cross-browser environment. However, as long as we register all event handlers through jQuery, we can safely use this method.
Next, we will delete the check statement event.target == this we just added and add some code in the button's click handler:

Copy code The code is as follows:

$(document).ready(function(){
$('#switcher .button').click(funtion(event){
//……
event.stopPropagation();
})
})

As before, you need to add a parameter to the function used as the click handler in order to access the event object. You can then prevent all other DOM elements from responding to this event by simply calling event.stopPropagation(). In this way, the button click event will be handled by the button, and only the button. Clicking elsewhere on the style converter collapses and expands the entire area.

3. Default operation

If we register the click event handler to an anchor element instead of an outer

, then we have to face another problem: when the user clicks the link, the browser will load a New page. This behavior is not the same concept as the event handler we discussed, which is the default action for clicking an anchor element. Similarly, when the user presses the Enter key after editing the form, the submit event of the form will be triggered. After this event occurs, the form submission will actually occur.
If we do not want this default action to be performed, calling the .stopPropagation() method on the event object will not help, since the default action does not occur in the normal event propagation flow. In this case, the .preventDefault() method can terminate the event before triggering the default action.
Tip .preventDefault() is usually used after some validation has been completed in the context of the event. For example, during form submission, we check whether the user has filled in the required fields, and if the user does not fill in the corresponding fields, then we need to prevent the default action. We discuss form validation in detail in Chapter 8.
Event propagation and default operation are two independent mechanisms. When either occurs, the other can be terminated. If you want to stop both event propagation and default action, you can return false in the event handler, which is a shorthand way of calling both .stopPropagation() and .preventDefault() on the event object.

Supplement:

Copy code The code is as follows:

//Click button event (change text style)
$(document).ready(function() {
$('#switcher .button').click(function() {
$('body').removeClass();
if (this.id == 'switcher-narrow') {
$('body').addClass('narrow');
}
else if (this.id == 'switcher-large') {
$('body').addClass('large');
}

$(' #switcher .button').removeClass('selected');
$(this).addClass('selected');
});
});

//Click the outer div of the button to trigger the event (hidden button)
$(document).ready(function() {
$('#switcher').click(function() {
$('#switcher .button').toggleClass('hidden');
});
});


The problem now is that when the button is clicked, At the same time, the hidden button event is triggered. This is caused by event bubbling.
In order to prevent the event from bubbling, you need to add a parameter to the hidden button function:
Copy the code The code is as follows:

$(document).ready(function() {
$('#switcher').click(function(even) {
if(even.target==this){
       $('#switcher .button').toggleClass('hidden');
     }
  });
});

even save the event object, even. The target attribute holds the target element where the event occurred. You can determine which element in the DOM received the event first. At this point the code ensures that the
is clicked and not its descendant elements.

This can also be done by modifying the behavior of the button to achieve the goal.

Copy code The code is as follows:

$(document).ready(function() {
$('#switcher .button').click(function(even) {
$('body').removeClass();
if (this.id == 'switcher-narrow') {
$('body').addClass('narrow');
}
else if (this.id == 'switcher-large') {
$('body').addClass ('large');
}

$('#switcher .button').removeClass('selected');
$(this).addClass('selected');
even.stopPropagation();
});
});

Prevent event bubbling with JS

Event bubbling: When an event is triggered on an element, such as the mouse clicking a button, the same event will be triggered in all ancestor elements of that element. This process is called event bubbling; the event bubbles up from the original element to the top of the DOM tree.
You can use JS to prevent js events from bubbling. Because of the differences in browsers, the JS writing methods of IE and FF are slightly different.
IE uses cancelBubble=true to prevent it, while FF needs to use the stopPropagation method.
The next complete code:

Copy the code The code is as follows:





无标题文档



点击aaaa会触发上层的onclick事件,点击bbbb不会触发上层onclick事件



 
   
   
 
 
   
   
 
 
   
   
 
  
aaaabbbbb
  



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Understand the event bubbling mechanism: Why does a click on a child element affect the event of the parent element? Jan 13, 2024 pm 02:55 PM

Understanding event bubbling: Why does a click on a child element trigger an event on the parent element? Event bubbling means that in a nested element structure, when a child element triggers an event, the event will be passed to the parent element layer by layer like bubbling, until the outermost parent element. This mechanism allows events on child elements to be propagated throughout the element tree and trigger all related elements in turn. To better understand event bubbling, let's look at a specific example code. HTML code: <divid="parent&q

Reasons and solutions for jQuery .val() failure Reasons and solutions for jQuery .val() failure Feb 20, 2024 am 09:06 AM

Title: Reasons and solutions for the failure of jQuery.val() In front-end development, jQuery is often used to operate DOM elements. The .val() method is widely used to obtain and set the value of form elements. However, sometimes we encounter situations where the .val() method fails, resulting in the inability to correctly obtain or set the value of the form element. This article will explore the causes of .val() failure, provide corresponding solutions, and attach specific code examples. 1.Cause analysis.val() method

Why does event bubbling trigger twice? Why does event bubbling trigger twice? Feb 22, 2024 am 09:06 AM

Why does event bubbling trigger twice? Event bubbling (Event Bubbling) means that in the DOM, when an element triggers an event (such as a click event), the event will bubble up from the element to the parent element until it bubbles to the top-level document object. . Event bubbling is part of the DOM event model, which allows developers to bind event listeners to parent elements, so that when child elements trigger events, the events can be captured and processed through the bubbling mechanism. However, sometimes developers encounter events that bubble up and trigger twice.

Why can't click events in js be executed repeatedly? Why can't click events in js be executed repeatedly? May 07, 2024 pm 06:36 PM

Click events in JavaScript cannot be executed repeatedly because of the event bubbling mechanism. To solve this problem, you can take the following measures: Use event capture: Specify an event listener to fire before the event bubbles up. Handing over events: Use event.stopPropagation() to stop event bubbling. Use a timer: trigger the event listener again after some time.

What scenarios can event modifiers in vue be used for? What scenarios can event modifiers in vue be used for? May 09, 2024 pm 02:33 PM

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)

Why does the event bubbling mechanism trigger twice? Why does the event bubbling mechanism trigger twice? Feb 25, 2024 am 09:24 AM

Why does event bubbling happen twice in a row? Event bubbling is an important concept in web development. It means that when an event is triggered in a nested HTML element, the event will bubble up from the innermost element to the outermost element. This process can sometimes cause confusion. One common problem is that event bubbling occurs twice in a row. In order to better understand why event bubbling occurs twice in a row, let's first look at a code example:

Which JS events don't bubble up? Which JS events don't bubble up? Feb 19, 2024 pm 09:56 PM

What are the situations in JS events that will not bubble up? Event bubbling (Event Bubbling) means that after an event is triggered on an element, the event will be transmitted upward along the DOM tree starting from the innermost element to the outermost element. This method of transmission is called event bubbling. However, not all events can bubble up. There are some special cases where events will not bubble up. This article will introduce the situations in JavaScript where events will not bubble up. 1. Use stopPropagati

What are the common ways to prevent bubbling events? What are the common ways to prevent bubbling events? Feb 19, 2024 pm 10:25 PM

What are the commonly used commands to prevent bubbling events? In web development, we often encounter situations where we need to handle event bubbling. When an event is triggered on an element, such as a click event, its parent element will also trigger the same event. This behavior of event delivery is called event bubbling. Sometimes, we want to prevent an event from bubbling up, so that the event only fires on the current element, and prevents it from being passed to superior elements. To achieve this, we can use some common directives that prevent bubbling events. event.stopPropa

See all articles