0

I'm trying to achieve card tilt effect on multiple cards. But its not working for some reason. Some of the solutions I tried.

  1. Selecting all cards and containers using document.querySelectorAll
  2. creating using forEach on the containers to create eventListeners and inside the function I created a forEach loop for the cards. Also, when it works it just make the same tilt on all containers.

//Card Animation
const container = document.querySelector(".card-container");
const card = document.querySelector(".card");
//Functions
function cardAnimation(e)
{
    let xAxis = (window.innerWidth / 2 - e.pageX) / 30;
    let yAxis = (window.innerHeight / 2 - e.pageY) / 30;
    card.style.transform = `rotateY(${xAxis}deg) rotateX(${yAxis}deg)`;
}
function cardAnimationEnter()
{
    card.style.transition = "none";
}
function cardAnimationLeave()
{
    card.style.transform = "rotateY(0) rotateX(0)";
    card.style.transition = "all .4s ease";
}
//Event Listeners
container.addEventListener("mousemove", cardAnimation);
container.addEventListener("mouseenter", cardAnimationEnter);
container.addEventListener("mouseleave", cardAnimationLeave);
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box; 
  }

body {
  overflow-x: hidden;
  perspective: 10000px;
 }
.card-group {
  display: flex;
  justify-content: justify;
  flex-direction: row;
  align-items: center;
  flex-wrap: wrap;
}
.card {
  transform-style: preserve-3d;
}
<div class="card-group">
        <div class="card-container">
          <div class="card">
            <img class="card-img" src="https://careerfoundry.com/en/blog/uploads/difference-between-ux-ui-ux-ui-min.png" alt="">
            <h1>This Is a test</h1>
          </div>
        </div>
        <div class="card-container">
          <div class="card">
            <img class="card-img" src="https://careerfoundry.com/en/blog/uploads/difference-between-ux-ui-ux-ui-min.png" alt="">
            <h1>This Is a test 2</h1>
          </div>
        </div>
</div>
7mo0do
  • 11
  • 2
  • [What Do You Mean “It Doesn’t Work”?](https://meta.stackexchange.com/q/147616/289905) – Sebastian Simon Dec 11 '20 at 13:13
  • it just replicate the same effect on the containers. – 7mo0do Dec 11 '20 at 13:14
  • Use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](https://developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](https://stackoverflow.com/tags/event-delegation/info) and [What is DOM Event delegation?](https://stackoverflow.com/q/1687296/4642212). – Sebastian Simon Dec 11 '20 at 13:18

0 Answers0