Ways to help parents disregard events initiated by their children

I have a situation where clicking on a child element should not trigger the parent element, but using event.stopPropagation() is not an option due to other event listeners waiting for the click event.

Specifically, when clicking on the dropdown of parent1 and then on the dropdown of parent2, the dropdown of parent1 should close and the dropdown of parent2 should open as expected. The problem arises in that the event bubbles up to the parent element, which should ignore it but is captured by other event listeners.

Visit this link for more details

Answer №1

If you want to maintain the @click handler on the parent element, one solution is to utilize the .self modifier:

<template>
  <div class="hello" @click.self="openAlert">
    <div class="hello_title">{{ title }}</div>
    <!-- There is another @click handler within the dropdown component -->
    <dropdown class="hello_dropdown" :dropdownId="id" />
  </div>
</template>

However, keep in mind that with this approach, the event will not trigger on clicks of any child elements. For instance, clicks on the div with the class hello_title will not trigger the openAlert handler.

In scenarios where the DOM tree is simple, you can easily navigate this limitation by adding separate handlers to each descendant. In more complex component hierarchies, this may not be an ideal solution.


If a more robust solution is necessary, you could create an independent "Event Bus" Javascript module that can be imported and used by multiple components. This module could serve as a wrapper for a map of strings to handler functions:

const map = {};

export function addEventListener(name, fn) {
  if (!map[name]) map[name] = [];
  map[name].push(fn);
}

export function emit(name, ...args) {
  if (map[name]?.length) {
    for (const fn of map[name]) {
      fn(...args);
    }
  }
}

Dropdown components can register their listeners on the event bus and emit appropriate events from a handler with stopped propagation. This eliminates the need to let the event bubble up to the document body. Consequently, the parent div can utilize the standard @click syntax without modifications, as clicks on the dropdown will be ignored.

<template>
  <div class="hello" @click="openAlert">
    <div class="hello_title">{{ title }}</div>
    <!-- The dropdown component uses a @click.stop handler, delegating to the event bus -->
    <dropdown class="hello_dropdown" :dropdownId="id" />
  </div>
</template>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Displaying a DIV inside an embedded DIV when selecting an option in HTML by utilizing JavaScript

My goal is to create a page where users initiate a questionnaire by clicking START in a web form - this action will open the DIV for the first question. As users answer each question (with yes/no choices), it will either display a specific DIV related to ...

Redirect to URL using Ajax upon successful completion

I'm facing an issue with my function as it doesn't redirect after a successful operation. I'm not sure why the redirection is not happening consistently. Sometimes, adding ...href after e.preventDefault(); seems to work. $('#nadwozie&a ...

What are the steps to effectively utilize an interface within a TypeScript file that contains its own internal import?

Currently, I am in the process of developing a React JavaScript project using WebStorm and attempting to enable type hinting for our IDEs (including VS Code) by utilizing TypeScript interfaces and JSDoc annotations. Our goal is to potentially transition to ...

An existing INPUT value can be modified by dynamically adding or subtracting values from SELECT OPTION

I currently have an <input readonly> field that displays the total_price value retrieved from a shopping cart stored in the database table. Moreover, I have included a <select> element with different transport options that can either increase o ...

Using Vue to access values in v-model:

I need to implement validations for a form with 30 fields by using getters and setters. However, it seems I cannot have computed and data values with the same name. Some examples suggest that setting the model and the computed property as the same can wor ...

I'm encountering an unfamiliar plugin type in Nuxt 3

Within my Nuxt 3 application, I have developed a custom plugin located in the plugins/ folder. // plugins/customPlugin.ts export default defineNuxtPlugin(() => ({ provide: { hello: (msg: string) => console.log(`This is your message: ${msg}` ...

Hiding both clear buttons in the MUI Autocomplete component on Chromium: A simple guide

The issue with the clear button is specific to Chromium; it does not appear in Firefox. Take a look at an example of a MUI React Autocomplete component displaying two clear buttons. Various solutions mentioned in this thread only hide the rightmost butto ...

Obtain the native element of a React child component passed through props, along with its dimensions including height and width

Is there a way in React to access the native HTML element or retrieve the boundaries of an element passed as a child in props? Consider the following component: class SomeComp extends Component { componentDidMount() { this.props.children.forEa ...

Tips for aligning a cluster of floating buttons at the center in Vuetify:

This is the code I am currently working with: <v-container height="0"> <v-row align="center" justify="center"> <v-hover v-slot:default="{ hover }" v-for="(option, index) in options" ...

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

steps to determine if a page is being refreshed

Is there a way to prevent the page from reloading when the user clicks the reload button in the browser? I attempted to use this code, but my break point is not triggering. ngOnInit() { this.router .events .subscribe((e: RouterEvent) = ...

React js: Caution - Ensure each child within a list is assigned a distinct "key" property

One of the most frequently asked questions in React is regarding the key prop in the Todo component. Despite passing the id and using it as the key, some users still encounter errors. Various solutions have been attempted without success. Even though the ...

Using jQuery to dynamically update the CSS of one table column depending on the attribute of another column

Welcome to my HTML table <!DOCTYPE html> <html> <body> <table> <thead> <th>Title1</th> <th>Title2</th> </thead> <tbody> <tr> <td><input type="checkbox" id=0 /></td> ...

In jQuery, utilizing dynamic class names with variables

I have a series of images with unique classes such as: .1a .2a .3a .4a ..... I am looking to toggle some other classes named .1b .2b .3b .. and so on so that: '.1a' toggles to '1b' '.2a' toggles to &ap ...

Twitter API causing issues with setTimeout function in Node.js

Attempting to read from a file and tweet the contents in 140 character chunks, one after the other has proven to be quite challenging. Despite verifying that other parts of the code are functioning correctly, using a simple for-loop resulted in tweets bein ...

Stop the button event from triggering

Although Sharepoint is available, I believe this question pertains more to javascript and cross browsing than Sharepoint. In my Sharepoint environment, I have a custom ribbon button that should trigger a workflow for a specific element in my library. I wo ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

Bar graph data remains unchanged after each iteration of the loop

I've been attempting to implement a for loop in a JavaScript bar graph that resets the bar height to 0 when a button is clicked, but it doesn't seem to be working as expected. I've tried checking the console in Google Developer tools for err ...

What is the solution for handling undefined errors that occur when employing d3.select(this) within a Vue methods hook?

Currently, I am in the process of transferring d3 graphs from another project to my personal Vue-based project. Most aspects are functioning as expected, except for aligning labels in the arcs of a pie chart using the arc.centroid(d) method. Two errors kee ...

What is the best way to generate a JavaScript variable using information from SQLite?

I found the examples provided in the JavaScript edition of the Missing Manual series to be extremely helpful! OG.Q. I have explored various options but have not been able to find a solution to my problem yet. This is what I am trying to achieve: Save u ...