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

HTML5 input type Color displays individual RGB values

This code snippet opens up a variety of options for the user to manipulate different color values such as R, G, B, HEX VALUE, HUE, etc. However, the specific requirement is to only extract the Red value. <input id="color_pick"type="color" value="#ff0 ...

How can the object currently being dragged be chosen using JQueryUI Draggable?

Working with JQueryUI draggable, I am interested in applying styling to the draggable element while it is being dragged. Various attempts have been made using code like this: $(".ui-widget-content").draggable({ drag: function(event, ui) { $(this).cs ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

Creating space between elements in CSS div elements

I've come across numerous resources on this topic that have already been answered, but none of them have provided a satisfactory solution. Here's the scenario: I have created a basic fiddle showcasing the desired behavior: @ See fidlle If I h ...

Incorporate Subtitles into Your Website Using JWPlayer

I want to incorporate Video Captions similar to those seen on Lynda.com, for example at The captions should synchronize with the player and also appear in a separate block of HTML below the player. I am using JWPlayer for my video and have successfully in ...

When the URL is modified, triggering an event to load

Is there a way to make a page load directly to a specific section and automatically open an accordion? For instance, I have a page with multiple accordions displayed vertically. I already know that using id's in the URL like page#accordion1 will scro ...

Error message: "Issue with exporting withRouter and withStyles in React"

Using react in combination with redux and material-ui, I am working on creating a component. Specifically, I am trying to write an export statement export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage)) However, I have encountered ...

Is there a way to place two input fields from different forms side by side on the same line?

Here are two forms extracted from an html page: <form method="get" action="search/s" id="number"> <div style="text-align: center;"> <input type="text" id="regNo" name="regNo" size="30" maxLength="50" > or ...

``There seems to be an issue with the functionality of the href link

Currently, I am utilizing purecss to design colorful buttons on my website. However, I am encountering an issue where the href link is not clickable even though the button displays correctly. <button class='pure-u-1 pure-button pure-button-primary ...

Unlocking the Magic of JSONP: A Comprehensive Guide

Currently attempting to utilize JSONP in order to work around Cross Domain challenges. I referenced this solution: Basic example of using .ajax() with JSONP? $.getJSON("http://example.com/something.json?callback=?", function(result){ //response data a ...

Modify the style of an element using a media query and Angular 4

Is there a way to update a class of an element based on the browser's width in my .ts file? matchMedia('(max-width: 400px)').addListener((mql => { if (mql.matches) { this.myclass = 'toggled'; } })); In the HTML, it shou ...

How to Ensure Screen Opens in Landscape Mode with Phaser3

https://i.stack.imgur.com/keCil.pngIn my Phaser3 game, I am trying to achieve the functionality where the game opens horizontally in a webview without requiring the user to rotate their phone. The vertical photo below shows the game in its current state. W ...

In the realm of JavaScript, what happens when a function yields yet another function while also welcoming another function as an argument?

After following a Node & Express project tutorial on YouTube, I encountered the following code snippet in an async JavaScript file: const asyncHWrapper = (fn) => { return async (req, res, next) => { try { await fn(req, res, next); } c ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

React State not updating when dealing with a nested object using hooks

As a newcomer to React, I've been experimenting with react-beautiful-dnd and hooks. However, I'm facing an issue where my state doesn't update when dragging elements. (Edit: I am aware that the logic only works for 'same category' ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

What is the best way to tally the number of occurrences a value is true within an hour or day using React?

I am developing an alarm application and I want to track the number of times the alarm has been triggered within an hour and a day. Utilizing redux toolkit, I manage the state of the alarm (on/off) and have a reducer called countAlarm to increase the count ...

What could be causing my CSS code to not function properly within Vue.js?

Having trouble with css in VueJs. I can't seem to figure out what I'm doing wrong. Generally, my scoped style css works fine in vuejs, I can target ids and classes without any issues. The problem arises when trying to change the internal css va ...

When you try to install @mui/material, it may cause a conflict with

I'm encountering an issue while trying to set up @mui/material npm install @mui/material However, during the installation process, I am getting this error message: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! ...