Stopping a parent's event from firing when clicking on child elements without interfering with the child element events

Having read several posts such as this one, I am exploring a method to click on the parent div for it to hide, without hiding when clicking on either the search box or the 'click for event 2' text.

I have tried using onclick stop propagation to prevent the div from hiding when clicking on the input box. However, applying the same logic to 'click for event 2' prevents the div from hiding and also stops the other event from occurring.

To sum up:
1. Clicking the first 'event 2' text should only change the background color between blue and red without hiding the lightgreen div.
2. Clicking the 2nd 'event 2' text should display an alert box but not hide the pink parent div

How can I achieve these goals? Following a recent question, I attempted adding 'preventPropagation' to different elements and made a few other efforts, all in vain.

I am fairly new to JS, so any explanation would be greatly appreciated. Thank you.

function doThis() {
  var el = document.querySelector('#test1');

  if (el.style.display === 'flex') {
      el.style.display = 'none';
      } else {
        el.style.display = 'flex';
      }
}


function andThis() {
  var x = document.querySelector('.test2');
   if (x.style.background === 'red') {
      x.style.background = 'blue';
      } else {
        x.style.background = 'red';
      }
}

function doThisTwo() {
  var re = document.querySelector('#test3');

  if (re.style.display === 'flex') {
      re.style.display = 'none';
      } else {
        re.style.display = 'flex';
      }
}

function andThisTwo() {
  alert('hi');
}
#test1 {
  background: lightgreen;
  display: flex;
}
.test2 {
  background: red;
}
#test3 {background: pink}
<button onclick='doThis()'>click me</button>

<div id='test1' onclick='doThis()'>
  text <input onclick='event.stopPropagation()' type="text">
  <span class='test2' onclick='andThis()'>click for event 2</span>
</div>

<br><br>
<button onclick='doThisTwo()'>click me too</button>

<div id='test3' onclick='doThisTwo()'>
  text <input onclick='event.stopPropagation()' type="text">
  <span class='test4' onclick='andThisTwo()'>click for event 2</span>
</div>

Answer №1

By passing the event as an argument to the hide function, such as doThis(event), you can access event.target (the element actually clicked by the user) within the function.

Therefore, if the class of the element clicked matches the class of the button event2, then the function should not be executed.

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

The Bootstrap nav-justified feature fails to utilize the entire width available

Have you heard of the bootstrap-4 class called nav-pill? It's meant to make links have equal width and occupy all horizontal space. To achieve equal-width elements, simply use .nav-justified, as suggested. This will ensure that nav links take up al ...

What is the most effective way to use checkboxes to apply multiple filters to an array of objects?

Let me simplify the description. Within the App component, I fetch data from a JSON file and store it in the flightsList array. My goal is to filter this array based on checkboxes selected in the FlightOptions and Airlines components. The issue that I&a ...

The program encountered an error while trying to access the undefined property '_header'

An issue arises when the app.use(express.static("web")) line is executed. var express = require('express')(); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); //app.get(&apo ...

fetch information using ajax and jquery

I'm facing an issue with my ajax request on my website. I'm trying to dynamically fetch pages from a database using jquery and ajax. However, I'm not getting any response, and I'm unsure whether the problem lies in my php code or my j ...

Can you tell me the XPath of this specific element?

Looking for the XPath of this specific element: <a> href="/resident/register/">Register another device </a> I initially tried $x("//*[contains(@href, 'resident/register')]") Unfortunately, no results were returned. Any other su ...

When crafting an XPATH expression, I am able to navigate within the #document element. Within this element, I must specify the path to the HTML body of my web page

I need assistance with my HTML page, can someone please help? Here is the XPath code I am using: (//span[text()='Information']//following::div[contains(@class,'edit-area')])[1]/iframe However, when I run my script, it says that there ...

Issue with array push not working within nested Promise

I recently encountered an issue with my Express API route that retrieves an artist's details along with an array of releases for that artist. My current goal is to iterate over this array, extract each URL, and then make additional API calls to retri ...

What is the best way to transform parameters in axios requests into objects?

Within my ReactJs app, I have implemented the following code: axios .get(`/shipping/get-shipping-values`, { params: { products: [ { ...product, quantity, }, ], ...

I prefer children to have their own unique style, instead of inheriting their parent's CSS

I currently have a project structured in the following way: There is an index page with a full layout Separate PHP files that are included in the index page Bootstrap is used in the index page, however, in some of the separate PHP files I also use jqgri ...

"Resolving the problem of populating an empty array with JSON

My JSON structure at the top level is set up like this: { "video": [], "messages": [], "notifications": [] } In the database output stored in a variable called "result," I have data that I want to add to the "vide ...

Encountering a Jquery 404 error while attempting to locate a PHP file through Ajax requests

I've been struggling with this issue for the past couple of hours, but I just can't seem to get it fixed. Here's my current file setup: classes -html --index.html --front_gallery.php -javascript --gallery.js I've been following a tuto ...

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

Unable to change Bootstrap variables within a Next.js project

I'm having trouble changing the primary color in Bootstrap within my NextJS project. I've tried different methods but nothing seems to work as expected. Here is the code snippet from my "globals.scss" file that I imported in "_app.js": $primary: ...

concealing directory titles within HTML and AJAX

What are the potential security risks associated with exposing PHP folder names? If there are risks, what methods can be used to conceal the folder names within html hyperlinks and ajax code? ...

Eliminate custom CSS generated by themes on WordPress category pages

I am a newcomer to the world of Wordpress and I'm currently in the process of making adjustments to an existing theme. The theme itself is generating custom CSS code and adding it to the wp_head section. add_action('wp_head', 'custom_c ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

Unlock the full potential of integrating external APIs with Next.js

As a newcomer to NextJs, I am facing the task of making calls to an external Python API from my frontend. Upon discovering NextJs's integrated API feature through creating folders in the app directory, namely api/resource/route, I am wondering what th ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Closing Note in Drupal

Is there a way to adjust the footer message in Drupal without logging into the dashboard? I've checked all the files in cPanel, but I can't seem to locate the actual HTML for the website. I am only able to customize the body content, not the fo ...