How come the click event is being activated on the child element despite using e.target?

I am encountering an issue with a function that switches between two colors when an element is clicked. The function works correctly on the parent element, but not on the child element. Can you help me understand why?

    <div class="parent red">
        <div class="child blue"></div>
    </div>
    <script scr="text/javascript" defer>
        let parent=document.getElementsByClassName("parent")[0];
        let child= document.getElementsByClassName("child")[0];

        function toggleColor(e){
            let background= e.target.classList;
            console.log(e.target);
            console.log("event fired")
            if(background.contains("blue")){
                e.target.classList.remove("blue");
                e.target.classList.add("red");
                console.log("event fired")
            }
            else if(background.contains("red")){
                e.target.classList.remove("red");
                e.target.classList.add("blue");
                console.log("event fired")
            }
        }

        parent.addEventListener("click",toggleColor,false);
        child.addEventListener("click", toggleColor,false);
    </script>

Answer №1

It seems likely that the issue you are experiencing is due to event propagation. When clicking on a child element, the click handler for the child element is executed first, followed by the click handler for the parent element. This could be causing unexpected behavior in your scenario.

To resolve this, consider adding e.stopPropagation() to your toggleColor function. This should ensure that everything functions as intended.

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

Creating a seamless navigation experience using Material UI's react Button and react-router-dom Link

Is there a way to have the Material UI react Button component behave like a Link component from react-router-dom while preserving its original style? Essentially, how can I change the route on click? import Button from '@material-ui/core/Button' ...

Can you provide instructions on utilizing WYSIWYG for real-time label editing?

I am currently developing an online survey creator. The structure of a Question entity is as follows: [Question] int QuestionId { get; set; } int QuestionNumber { get; set; } String QuestionText { get; set; } QuestionType QuestionType { get; } When prese ...

The perfect way to override jest mocks that are specified in the "__mocks__" directory

Within the module fetchStuff, I have a mock function named registerAccount that is responsible for fetching data from an API. To test this mock function, I've created a mock file called __mocks__/fetchStuff.ts. Everything seems to be functioning corre ...

Running HTML code within a DIV using JavaScript

Although I've come across questions like this before, mine has a unique twist. I crafted an HTML code that is capable of running another HTML code within a <div>. The resulting page appears as follows: https://i.sstatic.net/zXgG7.png The HTML ...

Using PHP to read an image blob file from an SVG

Currently, I am utilizing the Raphael JS library on the client-side to generate a chart in SVG format. However, my goal is to make this chart downloadable, which poses a challenge since SVG does not natively support this feature. Initially, I attempted to ...

What is the best way to transfer information from a layout to its children within the app directory of Next.js?

One scenario I encounter frequently is the need for a button in a layout to toggle something within the components it contains. For instance, you might have a notifications button in a fixed layout that triggers a side panel to open in the main application ...

Executing a callback function within two nested functions

I am having trouble with the callback function that is being called inside a function which in turn calls another function. exports.user = function(userName, pwd, callback) { db.User.findOne({'userName': userName}, function(error, obj) { ...

By default, use jQuery to load the content of a div

Upon page load, I am looking to display the content within #destiny2. This section includes text and images, as well as additional content for three categories. Initially, the first category should be shown without requiring a click. Subsequently, clicking ...

When utilizing MUI's ThemeProvider, it may result in encountering errors that display as "undefined"

I am facing an issue with my MUI application. Everything was working perfectly until I decided to implement a ThemeProvider. It seems that as soon as I add the ThemeProvider, the application breaks and all MUI components I'm using start throwing undef ...

How is it that a callback function can successfully execute with fewer arguments provided?

Code I'm really intrigued by how this code functions. In the verifyUser function, it passes a callback function as the fourth argument to the verifyToken function. However, upon examining the verifyToken function itself, I noticed that it only has th ...

Inaccurate ray tracing using an orthographic camera in three.js

Currently working on a 2D CAD drawing viewer using the three.js library. I need the ability to click on objects within the scene to perform operations. However, when utilizing an orthographic camera, I've noticed that the precision of the three.js ra ...

Baffled by the intricacies of jQuery

As a newcomer to jQuery, I stumbled upon this code snippet and am curious about its function. It seems like it is replacing an element with the id reveal to a link with the class html5lightbox and id reveal. However, the part that puzzles me is $( '#r ...

Retrieving data from a JSON using Typescript and Angular 2

Here is an example of what my JSON data structure looks like: { "reportSections": [ { "name": "...", "display": true, "nav": false, "reportGroups": { "reports": [ { "name": "...", "ur ...

What is the best way to determine which array to manipulate based on its current state?

I'm facing an interesting challenge where I need to determine which array to map over based on the length of shownAppointments. {shownAppointments.length ? shownAppointments .flat() .map((appointment) => ( ...

Utilizing data attributes to configure jQuery plugin settings

Having trouble assigning options to an array value in a jQuery plugin using data attributes. When referencing the data attribute with a class selector: $('.tm-input').tagsManager( { prefilled: $('.tm-input').data('loa ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

Tips for resolving the error "Parsing near 'Unexpected end of JSON input while parsing...' for...'mocha':'^3.2.0','s'":

Once I've successfully set up react and react-dom, the next step is to install webpack. However, I encountered an error during this process. To troubleshoot, I decided to install babel-loader first to ensure that both npm and my internet connection a ...

Utilizing the Twitter API 1.1 to retrieve a list of tweets

As I work on updating my CMS component, I am incorporating integration with the Twitter API to fetch and showcase a list of tweets related to a user or search query. I have chosen to utilize the Twitter Restful API v1.1 as the 1.0 version is set to be disc ...

JavaScript - Functions in objects losing reference to previously created object properties

Having trouble with my Candy function. When I create an object of the Candy function, all attributes are created correctly. However, when I try to run the draw function, it always uses the properties of the second object created instead of the one I want. ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...