What could be causing my jQuery click event to behave as if I triggered a click on the parent element?

I have created multiple child divs within a parent div. All the divs are positioned, with the parent div set to absolute and the child divs set to relative. The z-index of the parent div is 400, while the child divs have a z-index of 500.

However, when I click on any child div, jQuery is not detecting the parent div using the click function. I am unsure why these codes are not working as expected.

If anyone could assist me in resolving this issue, it would be greatly appreciated.

ID of the Parent div: "#cardslayer"

Class of the Child divs: ".cardinlayer"

-HTML:

<body>
<div id="cardslayer"></div>
</body>

-CSS:

#cardslayer {
    position: absolute;
    width: 960px;
    height: auto;
    top: 0;
    left: 0;
    z-index: 400;
    display: none;
}

.cardinlayer {
    width: 100px;
    height: 125px;
    margin: 10px;
    position: relative;
    z-index: 500;
    display: none;
}

-JQUERY: (Includes some CSS styling through jQuery)

var hazakstr = "";
var i = 0;

$("#button").click(function(){
    hazakstr = "<center>";
    for(i=0; i<22; i++) {
        if(level_owner[i] == -1) {
            hazakstr += "<div class='cardinlayer' id='house" + i + "' style='background: url(../houses/" + i + ".png); background-size: 100px 125px; background-repeat: no-repeat;'></div>";
        }
    }
    hazakstr += "</center>";
    $("#cardslayer").css("display", "block");
    $("#cardslayer").html(hazakstr);
    $(".cardinlayer").css("display", "inline-block");
    i=((567 - $("#cardslayer").height()) / 2);
    $("#cardslayer").css("height", 567 - i + "px");
    $("#cardslayer").css("padding-top", i + "px");
});

HTML content added to #cardslayer after loop completion:

HTML:

<div id="cardslayer" style="display: block; height: 507px; padding-top: 60px;">
    <center>
        <div class="cardinlayer" id="house0" style="background: url(&quot;../houses/0.png&quot;) 0% 0% / 100px 125px no-repeat; display: inline-block;"></div>
        <div class="cardinlayer" id="house1" style="background: url(&quot;../houses/1.png&quot;) 0% 0% / 100px 125px no-repeat; display: inline-block;"></div>
        .
        .
        .
        .
        <div class="cardinlayer" id="house21" style="background: url(&quot;../houses/21.png&quot;) 0% 0% / 100px 125px no-repeat; display: inline-block;"></div>
    </center>
</div>  

Despite creating a click function for .cardinlayer, it is not functioning properly.

$(".cardinlayer").click(function(){
      alert("Cardinlayer");
});

I also attempted a click function for all div elements:

$("div").click(function(){
    alert($(this).attr("id"));
});

However, upon clicking a .cardinlayer element, the return value is #cardslayer instead of the specific house ID like #house1.

#cardslayer is the parent container, and .cardinlayer(s) are its children.

Image illustrating the issue: https://i.sstatic.net/QHyut.jpg

In the image, the red section represents the parent, while the blue sections represent the children. Upon clicking a card, jQuery incorrectly identifies that the faded black background (parent) has been clicked.

I seek assistance from anyone who can help me resolve this problem effectively. Thank you and have a great day!

Answer №1

Modifying the click event is possible with additional functions like stopPropagation or preventDefault. (For more information, visit: Event on MDN)

To visualize this in action:

let hazakstr = "";

const cardHtml = ({ i }) => {
  return `
    <div
      id="house${i}"
      class="cardinlayer"
      data-idx="${i}"
    >
      HOUSE ${i}
    </div>
  `
}


jQuery("#button").on('click', function() {
  for (let i = 0; i < 22; i++) {
    hazakstr += cardHtml({ i })
  }
  $("#cardslayer").html(hazakstr);
});

jQuery("#cardslayer").on('click', '.cardinlayer', function(e) {
  e.stopPropagation() // this stops the event from propagation
  const { idx } = $(this).data()
  alert(`Clicked house card: ${idx}`)
})
.container {
  position: relative;
}

#cardslayer {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
}

.cardinlayer {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 125px;
  padding: 8px 16px;
  background-color: rgba(255, 0, 0, 0.3);
  -webkit-transition: background-color 0.25s ease-out;
  -moz-transition: background-color 0.25s ease-out;
  -o-transition: background-color 0.25s ease-out;
  transition: background-color 0.25s ease-out;
  cursor: pointer;
}

.cardinlayer:hover {
  background-color: rgba(255, 0, 0, 0.9)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button">CLICK</button>
<div class="container">
  <div id="cardslayer"></div>
</div>


EDIT / SUGGESTION:

If feasible, I recommend avoiding using jQuery. Here's an updated approach using Vue:

Vue.component('HouseCard', {
  props: ['idx'],
  methods: {
    onClick({ idx }) {
      alert(`Clicked house: ${ idx }`)
    },
  },
  template: `
    <div
      class="cardinlayer"
      @click.stop="() => onClick({ idx })"
    >
      HOUSE {{ idx }}
    </div>
  `
})

new Vue({
  el: "#app",
  data() {
    return {
      houses: [],
    }
  },
  methods: {
    addHouse(houses) {
      return [...houses, houses.length]
    },
    add1House() {
      this.houses = this.addHouse(this.houses)
    },
    add22Houses() {
      let ret = this.houses
      for (let i = 0; i < 22; i++) {
        ret = this.addHouse(ret)
      }
      this.houses = ret
    }
  },
  template: `
   ...
  `
})
...
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

Alternatively, you can utilize React:

...
...
...

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

Utilize a Jquery object as a key within a different object

Is it possible to include a jQuery object as a key in a blank object in JavaScript? For instance: var obj = {};//blank object var myId = $("#myId");//jQuery Object var myId2 = $("#myId2");//another jQuery Object obj[myId] = "Trying to add myId as a key" ...

What could be causing the occasional appearance of a tiny glitch, like a pixel dot, below a menu item when utilizing this hover effect?

Occasionally, a tiny dot appears almost imperceptibly, like the one below the "prices" menu item: https://i.stack.imgur.com/kyaP3.png This is the hover effect code I created: :root { box-sizing: border-box; } *, *::before, *::after { box-sizing: ...

execute field function prior to sorting

Currently, I am building a graphql server in express and using a resolver to modify my fields based on user input from the query. The issue arises from the transformer function returning a function. My goal is to sort the results by a field determined by ...

Responsive Gallery Grid Slider with uniform height boxes

Looking to develop a responsive gallery grid slider with equal height boxes. For instance, at 650px wide or wider, display 3 columns and 2 rows. When the width is 550px or less, switch to 2 columns and 3 rows. If the width is 450px or less, go down to 1 ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

The ForbiddenError has struck again, this time wreaking havoc in the realms of Node.js, Express.js

I am currently adapting this GitHub sample application to utilize Express instead of KOA. However, I am encountering an Access Denied issue when the / route in Express attempts to load the index.html. What specific modifications are required in the code be ...

Is it possible to nest a parsys within another parsys in this context?

On my webpage, I have a paragraph system (parsys) with a component that contains two inner paragraph systems. When I try to add a rich text component to each of these inner paragraph systems, the components overlap and become uneditable. Is it possible t ...

Ways to enhance radio imagery selection?

I'm just starting out with JS and could really use some guidance on how to improve my code. I think it might need a single function for all options, but I'm not sure. It's working fine right now, but I have a feeling it could be better ;) H ...

Utilizing Query Data Source in ASP.NET MVC for Enhanced JQuery DataTables Experience

Overview I am venturing into ASP.NET from ColdFusion and seeking guidance on replicating a similar technology in MVC 5. My current approach involves running a query in a CFC to populate a DataTable, where the results are then arranged in JSON format and ...

Navigating the root path that is defined in the gulp task within an Angular application

My current task involves building my application with the following code: const app = new Metalsmith(config.styleguide.path.root); app.use( msDefine({ production: false, rootPath: '/' }) ); app.use( ms ...

Changing the text color of Material UI Accordion Summary upon expansion

How can I update the color of an Accordion summary text in Material UI when it is expanded? <Accordion expanded={expanded === 'panel1'} onChange={handleChange('panel1')} className={classes.root}> <AccordionSummary ...

What might be stopping Javascript from saving the value to the clipboard?

On my ASP.Net website, I am incorporating basic Javascript functionality. One particular task involves calculating a value and saving it in a hidden textbox, like this: <asp:LinkButton ID="LinkButtonShare" runat="server" CssClass="btn btn-success" OnC ...

Challenges with registering on Ajax platform

I'm currently facing an issue with my login/sign up process and I can't seem to figure it out. I have shared a jsfiddle link with the code, but I am struggling to identify the problem. https://jsfiddle.net/Zemanor/fuzrkw16/1/ Whenever I submit ...

Horizontal rule spans the full width of the content, appearing within an ordered list

Check out this example to see the issue with the horizontal rule not extending all the way across under the number. I've tried using list-style-position:inside;, but that interferes with positioning the number correctly due to the left image being flo ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

Issue with Table Element's Full Width Within Parent Element

Here is a demonstration of the scenario in JSFiddle I have made updates to the JSFiddle demonstration here: http://jsfiddle.net/x11joex11/r5spu85z/8/. This version provides more detailed insight into how the sticky footer functions well, albeit with a hei ...

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

Can someone assist me in understanding the proper syntax for the Node.js function that inserts a document into Watson's Discovery service from the watson-developer-cloud library?

I'm attempting to upload JSON documents into a Discovery collection using the Node.js watson-developer-cloud JDK. Here is the relevant code snippet: const DiscoveryV1 = require('watson-developer-cloud/discovery/v1'); const discovery = new D ...

unable to update database using jquery ajax

Hello everyone, this is my first time posting on Stackoverflow! I am facing an issue while trying to run an "Insert" query using Jquery's $.ajax function. Upon checking the network tab on Chrome Dev Tools, it seems like my file is being loaded but th ...

The Bootstrap menu seamlessly extends beyond the edge of the screen

Whenever I try to zoom in on my page, the navigation bar doesn't collapse as expected. Instead, it overflows off the page. This issue persists when viewing the website on mobile devices in landscape mode. Although I am using the jQuery mmenu plugin, ...