Home > Software engineering >  Click event not returning the correct element properly
Click event not returning the correct element properly

Time:06-13

I am trying to create a card that rotates on click. It is working but I want to use the onclick event to add the 'is-flipped' class to the classlist of div.card. When I console log the event it shows target as <div >front</div> and currentTarget as null. I thought this was due to absolute positioning so I tried z-index: 100 still not working. Why is this happening and how can I get the .card div.

// var card = document.querySelector(".card");
// card.addEventListener("click", function () {
//     card.classList.toggle("is-flipped");
// });

function handleCardClick(e) {
    // e.stopPropagation();
    console.log(e);
}
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: "Poppins", sans-serif;
}

body {
    font-family: sans-serif;
}

.wrapper {
    width: 200px;
    height: 260px;
    border: 1px solid #ccc;
    margin: 40px 0;
    perspective: 600px;
}

.card {
    width: 100%;
    height: 100%;
    transition: transform 1s;
    transform-style: preserve-3d;
    cursor: pointer;
    position: relative;
    z-index: 100;
}

.card.is-flipped {
    transform: rotateY(180deg);
}

.card__face {
    position: absolute;
    width: 100%;
    height: 100%;
    line-height: 260px;
    color: white;
    text-align: center;
    font-weight: bold;
    font-size: 40px;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
}

.card__face--front {
    background: red;
}

.card__face--back {
    background: blue;
    transform: rotateY(180deg);
}
<div >
    <div  onclick="handleCardClick(event)">
        <div >front</div>
        <div >back</div>
    </div>
</div>

<div  onclick="handleCardClick(event)">123456789</div>

CodePudding user response:

in order to manipulate with classes on 'card' element try:

const card = document.querySelector('.card');
card.addEventListener('click', function(){
 card.classList.toggle('is-flipped')
})

if you want to use onclick="" then you should add "pointer-events: none;" property to .card child elements

.card__face {
pointer-events: none;}

and

function handleCardClick(e) {

const currentEl = e.target;
currentEl.classList.toggle('is-flipped')}
  • Related