Trigger the onClick event of an element only if it was not clicked on specific child elements

<div onClick={()=>do_stuff()}>
  <div classname="div-1"></div>
  <div classname="div-2"></div>
  <div classname="div-3"></div>
  <div classname="div-4"></div>
  <div classname="div-5"></div>
</div>

When you click on the parent element, it will trigger a function called do_stuff(), but this should only happen if the click did not target elements with class names like div-4 or div-5.

If you are using React, how would you implement this functionality?

Answer №1

event.stopPropogation() is the solution to this issue.

<div onClick={()=>do_stuff()}>
  <div classname="div-1"></div>
  <div classname="div-2"></div>
  <div classname="div-3"></div>
  <div classname="div-4" onClick={(event) => event.stopPropogation()}></div>
  <div classname="div-5" onClick={(event) => event.stopPropogation()}></div>
</div>

When dealing with nested HTML elements, click events follow a specific order up the hierarchy. Child components' onclicks are triggered first, followed by parent components' onclicks. Regardless of how deeply nested the elements may be, click events always start at the lowest nested level and work their way up through 'propagation'. To prevent clicks from propagating further up, simply invoke stopPropogation(). Once the callback with stop propagation is executed, the remaining call stack is cleared.

Answer №2

To verify the event target, you can use event.target in conjunction with Element#matches.

function handleEvent(event) {
  if (!event.target.matches('.div-4, .div-5')) {
    console.log('click');
  }
}
<div onClick={handleEvent}>
    { /* ... */ }
</div>

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

Semantic UI Footer allows you to easily create a stylish

Greetings! I'm new to the semantic-ui framework and I'm encountering an issue with the footer. My goal is to have the footer always stay at the bottom of the page without being fixed. Here's a snippet of my simple HTML code: <!DOCTYPE h ...

"Why does the font on my website look different on my computer before I upload it to my web host? How can I fix

I am currently developing a website and have chosen the font "PT Sans Narrow" for it. Unfortunately, it seems that Chrome and many other browsers do not support this font by default. Is there a way to include the PT Sans Narrow font with the website when ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Struggling with React: Attempting to store retrieved data in a variable, only to find the variable empty

After fetching JSON data using async await, I attempted to store the fetched data in a variable so that it can be used with a map function in my component. While the data is properly received within the function (confirmed by an alert) and displayed cor ...

The event failed to initiate

I have an event that is fired when the number value changes in the <input type="number"> below: <input type="number" inputmode="numeric" pattern="[0-9]*" size="4" class="lorem" value="0" step="1"> <input type="button" class="minus" value=" ...

Refreshing html in nodejs after a fetch promise remains in a pending state

I am facing an issue with the `then` method in Express and Node.js as it is logging a promise that remains pending. edit().then(data => console.log(data)); Below is the code for the edit function: async function edit(data, id) { let response = aw ...

Troubleshooting Next.js 13 Fetch Failed Error: Solutions to resolve this issue

During my exploration of the Next 13 beta version, I encountered a peculiar issue. My goal was to retrieve data from the server-side and display it on the page. However, the "fetch" operation failed on the server side. Below is the code snippet for the Nex ...

Retrieving the selected value from a dropdown using jQuery's `$('#id').val()` may not always provide the desired result

I am having trouble retrieving the selected value from a dropdown menu as it keeps returning either an empty string or undefined results. My HTML code is structured like this: <div class="input-group" style="padding-bottom: 10px;"> <span id= ...

Verify if the button is assigned a specific class, then generate a 'completed' div

I'm new to working with Jquery and I have a question. In my upload form, when something is uploaded the upload-button changes class from: <a class="upload-button upload buy" id="upload-button"><span>Upload a document</span></a> ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

Can someone help me troubleshoot this issue with my code so that my website can open in a blank page using about:blank?

I'm currently facing an issue while trying to make one of the pages on my website open with an about:blank URL upon loading. Despite embedding the code in my index.html file, it doesn't seem to be functioning properly. Here's the code I&apos ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

CSS loop to centrally align divs

I am facing an issue where I want to center the divs in a panel. Each div is generated within a for-each-loop inside the panel. However, the problem arises when they are displayed as block elements: When I try floating them left, they end up looking like ...

Acquire an OAuth2 Refresh Token for accessing Google Services within a ReactJs project

I am currently facing a particular issue that requires some assistance. In my ReactJs project running on Google AppEngine, I have implemented a class for accessing various Google Services (such as BigQuery, Drive, GMail...) using the OAuth2 token. The con ...

Fetching data from a server using Angular and displaying it in controllers

I am currently working on a project where I need to retrieve JSON files and their content using a factory in AngularJS. My main goal is to make this data accessible to other controllers, but I am struggling with getting the factory to return the deityData. ...

Steps to Make a White Content Box on Top of an Image Background using HTML/CSS

I am currently struggling with overlaying a white box on top of my background image in order to have my text inside the box for a more visually appealing look. Despite trying to add CSS code like this: .white-box { position: absolute; background-c ...

"Unlocking the power of your device's microphone with

Hello, I'm wondering if it's possible to utilize a device's microphone through trigger.io. Perhaps by integrating the native plugin functionality and creating a wrapper for microphone access using a forge native API, or exploring alternative ...

Can React be integrated with GitHub Pages despite its static website nature?

Is it possible to use Node for server-side functionality on a github.io site, even though github.io is typically used for static websites? I've seen tutorials on incorporating React, but unsure about integrating server-side programming. Thank you in a ...

Center Align Images in HTML List Items

Hey there! I'm currently diving into the world of web development with responsive design, but I'm still a bit of a newbie. So please bear with me as I try to explain my issue in detail. If you need more information, just let me know! My current ...