Home > other >  Why is my jQuery click handler acting as though I clicked on the parent element?
Why is my jQuery click handler acting as though I clicked on the parent element?

Time:01-06

I created lot of child divs in parent div. All divs positioned, parent div is absolute, child divs are relative. Parent div z-index is 400, child divs are 500.

When I clicked any child div then jQuery detect parent div with clicked function. I don't understand why isn't working these codes.

So I hope anyone can help me this situation.

Parent div ID: "#cardslayer"

Child divs class: ".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: (And some style in css with jquery function.)

  var hazakstr = "";
  var i = 0;
  

  $("#button").click(function(){
      hazakstr = "<center>";
      for(i=0; i<22; i  ) {
        if(level_owner[i] == -1) {
            hazakstr = hazakstr   "<div class='cardinlayer' id='house"   i   "' style='background: url(../houses/"   i   ".png); background-size: 100px 125px; background-repeat: no-repeat;'></div>";
        }
      }
      hazakstr = 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");
  });

Added html to #cardslayer when loop is ended. Code like this:

HTML:

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

So after all, I created click function for .cardinlayer. And its not working.

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

I tried this click function for .cardinlayer

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

When I clicked one .cardinlayer return value is #cardslayer, not #house1 or any #house.

#cardslayer is parent and .cardinlayer(s) are childs.

Picture of the problem: https://i.imgur.com/DjWcIKK.jpg

Red is parent, blue are childs. So when I click any card jquery is not detect. Jquery think I clicked the faded black background. (parent).

I hope anyone can help me. Have a nice day, and thanks.

CodePudding user response:

There are modifiers to the click event, like stopPropagation or preventDefault. (More info: Event on MDN)

To see it in action:

let hazakstr = "";

const cardHtml = ({ i }) => {
  return `
    <div
      id="house${i}"
      
      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 >
  <div id="cardslayer"></div>
</div>


EDIT / SUGGESTION:

I'd suggest that you don't mess with jQuery, if possible. Here's a bit updated thing in Vue:

Vue.component('HouseCard', {
  props: ['idx'],
  methods: {
    onClick({ idx }) {
      alert(`Clicked house: ${ idx }`)
    },
  },
  template: `
    <div
      
      @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: `
    <div>
      <button @click="add1House">ADD 1 HOUSE</button>
      <button @click="add22Houses">ADD 22 HOUSES</button>
      <br />
      <div
        
      >
        <div
          id="cardslayer"
        >
          <house-card
            v-for="(house, idx) in houses"
            :key="idx"
            :idx="idx"
          ></house-card>
        </div>
      </div>
    </div>
  `
})
.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/vue/2.5.17/vue.js"></script>
<div id="app"></div>

or the React solution:

const { useState } = React

const HouseCard = ({ idx }) => {
  const handleClick = () => {
    alert(`House clicked: ${idx}`)
  }
  return (
    <div  onClick={handleClick}>
      HOUSE { idx }
    </div>
  )
}

const App = () => {
  const [houses, setHouses] = useState([])
  
  const addHouse = (houses) => [...houses, houses.length]
  const add1House = () => setHouses((prev) => addHouse(prev))
  const add22Houses = () => {
    for(let i = 0; i < 22; i  ) {
      setHouses((prev) => addHouse(prev))
    }
  }
  
  return (
    <div>
      <button onClick={add1House}>ADD 1 HOUSE</button>
      <button onClick={add22Houses}>ADD 22 HOUSES</button>
      <div >
        <div id="cardslayer">
          {
            houses.map((_, idx) => <HouseCard idx={idx} />)
          }
        </div>
      </div>
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);
.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://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>

<div id="root"></div>

  •  Tags:  
  • Related