JavaScript

Prevent click on outer element while clicking on inner element – Javascript

Share your learning

How can I prevent clicking on the outer element while clicking on the inner element with js events?

It is quite simple, let’s see the below example code.

<div id=”parent_element” >



So, when we click on the inner element, it will actually trigger the two events one is the inner element and another will be of the parent element.

This is also called event bubbling in javascript. Where Bubbling means the most of the javascript events trigger from target element to its parent elements.

Event bubbling start from bottom to up elements.

Javascript example to use event stopPropagation

Javascript code is as given below.

document.querySelector("#parent_element").addEventListener('click', function() {
 alert('outer element');
})

document.querySelector("#child_element").addEventListener('click', function(e) {
 e.stopPropagation();
 alert('inner element');
})

In the jQuery use of event stop propagation

In jQuery the solution will be like below.

$(“#parent_element”).on(‘click’, function() {
 alert(‘outer element’);
})

$(“#child_element”).on(‘click’, function(e) {
e.stopPropagation();
 alert(inner element’);
})

Hence, we can use stop propagation on the inner element to prevent its click bubbling to the outer element.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago