Ways to avoid Parents Click Event from triggering during a Child's (Grandchild's) click event

My parent div has a unique feature where clicking on it reveals one of the child divs, and clicking again toggles the visibility of the child div. Inside this child div, there is a switch toggle that functions as a hidden checkbox. The issue I'm facing with my code is that when I click on the switch toggle, it triggers both the switch event and the parent click event.

I have attempted various solutions from Stack Overflow for similar questions, such as using e.stopPropagation(); on the child click event and if(e.target == this) on the parent click event, but none of them have resolved the problem. Any assistance would be greatly appreciated.

Please refrain from marking this as a duplicate, as I have tried all suggested solutions without success. Thank you.

Demo: jsfiddle

Answer №1

Preventing propagation on the checkbox's "change" event does not stop the click event that triggers the change from reaching its ancestors.

To prevent the click event from propagating, you can use the following code on the <label> (or any ancestor between the checkbox and the parent block):

$('.switch').on('click', function(e) {
  e.stopPropagation();
});

Check out this example:

$(".parent-block").on('click', function() {
  $(this).find("i").toggleClass("fa-chevron-down");
  $(this).find("i").toggleClass("fa-chevron-up");
  $(this).children(".second-child").slideToggle();
})

$("input[type=checkbox]").on('change', function() {
  if ($(this).is(":checked")) {
    $(this).closest('.switch-toggle-div').children('.on-off-label').html("ON");
  } else {
    $(this).closest('.switch-toggle-div').children('.on-off-label').html("OFF");
  }
});

$('.switch').on('click', function(e) {
  e.stopPropagation();
});
.parent-block {
  border: 1px solid Blue;
  border-radius: 5px;
  margin-bottom: 9px;
  cursor: pointer;
}

/* CSS styles here */

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<div class="parent-block">
  <div class="first-child">
    <p>News</p>
    <i class="fas fa-chevron-down"></i>
  </div>

  /* HTML structure goes here */

</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

Is there a way to transmit a div using Node.js?

Scenario: I am developing a web application that allows users to draw on a canvas, save the drawing as an image, and share it with others using Node.js. Current Progress: Drawing functionality (real-time updates on both clients). Saving the canvas as a ...

Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something? I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive: angular.js:12701 POST 500 (Internal Server Error ...

When hovering over the sidebar, it smoothly slides out. (ideally using only CSS)

I've been spending my free time working on a website, but I'm struggling to figure out how to create a navigation similar to the one featured on FontShop's site: . I want it so that when you hover over their logo (or in my case, a blank rect ...

The jQuery $.change function is not functioning properly when used with a cloned select element

In my table, there is a button that allows you to add a new row by cloning the last one. Each row contains a <select> with a different name (0-9), all having the class .variable_priority. When clicking the button, the row clones successfully and the ...

Unlocking the Power of VueJS Mixins in an External JS Library

I'm currently using a 'commonLibrary.js' in my Vue application. One of the functions in this library that I find particularly useful is: var defaultDecimalRounding=3 function formatNumber(number) { if (isNaN(number.value) == tr ...

What is the process for combining two elements using tailwind?

I am trying to stack two elements on top of each other using tailwind CSS. Here is what I have attempted: <div class = "w-10 h-10" id="container"> <button class = "relative w-4 h-4 bg-red"> Started </button> ...

Tips for locating the index of the previously selected active class

I am currently working on a slider and have made progress up to this point. However, I am facing an issue where I cannot proceed because I need to identify the index of the item from which I removed the last active class before the click event occurs. My ...

The importance of precision in a written text

When it comes to being specific, I usually pride myself on my skills. However, there's one particular challenge that I can't seem to crack. Here's the scenario: Imagine you have a list structured like this: <ul class="dates"> < ...

Having trouble iterating through a grouped array in JavaScript?

Regrettably, I am facing issues once again with my grouped messages. Although I have received a lot of assistance from you previously, I still find myself struggling and hesitant to ask for help again. Initially, my objective was to group messages based o ...

Display or Conceal a DIV depending on a PHP jQuery variable

Is there a way for me to Hide/Show a DIV based on a Variable? Here is what I currently have. The variable is posted into an INPUT <input type="text" id="showhidediv" name="showhidediv" value="<?php echo $ta; ?>"> This is the jQuery code I am ...

Vue.js does not display HTML properly within the vue-swal component

I'm currently working on integrating HTML content into a Sweet Alert popup using this code snippet Link: https://www.npmjs.com/package/vue-swal this.$swal({ title: '<i>Custom HTML</i>', html:`This is an <em> em ...

Stagnant className in map persisting despite changes being made

I am in the process of updating my react className based on changes to the active status within the sites variable, which is iterated over with a map function. The issue I'm facing is that the 'inactive' className persists even when the act ...

Issue with Firefox compatibility in Backbone.js

Greetings! I am currently utilizing Backbone.js and require.js for my application, experiencing difficulty with template rendering in Firefox. Interestingly, it works without issues in both Chrome and IE. Allow me to present the code responsible for rende ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Analyzing viewer engagement by monitoring the duration of video watched using JavaScript

I need a way to monitor video views for individual users, using a table in the database called Viewings. Each viewing is associated with both a user and a video, and keeps track of the duration watched as well as the percentage of the video completed. Whe ...

Using Jquery's closest technique to target a class located outside of the parent div

I am having trouble accessing a class outside of its parent div $(document).on('click', '.delete_photo', function(event){ var del_id = $(this).attr('id'); $.ajax({ type:'POST', cache: false, url:&apo ...

Ways to properly release file descriptors in write streams

I'm currently working on a code snippet that showcases what I'm aiming to achieve: const fs = require('fs'); var stream = fs.createWriteStream('/tmp/file'); stream.once('open', function(fd) { for (var i = 0; i ...

Is there a way to remove information with react and axios?

While working on a project, I encountered an issue with using .map() to create a list. When I console log the user._id on my backend, it displays all the ids instead of just the one I want to use for deleting individual posts by clicking a button. Each pos ...

The condition is not established by the Firestore where clause

I'm working on a function that includes two where clauses. My objective is to verify the existence of a document based on the presence of two specific IDs. However, when I execute the function, it retrieves all the records in the collection instead. C ...

interacting with data tables using a jQuery selector or through an application programming

I encountered a problem like the following: First, I attempted to initialize the datatable as shown below: var oTable = table.dataTable(); Although my script ran well, I found that I couldn't use the datatables ajax reload function. oTable.ajax.rel ...