I have this 3d parallax effect when the mouse hovers over the card. But I don't know how to make it return to its original position when the mouse is no longer on it.
let cardParallx = document.querySelector('.card-active');
cardParallx.addEventListener('mousemove',(e)=>{
let x =(window.innerWidth/2 - e.pageX)/30;
let y =(window.innerHeight/2 - e.pageY)/30;
cardParallx.style.transform =`rotateX(${-y}deg) rotateY(${-x}deg)`;
});
<div >
<img src="https://placekitten.com/200/300">
</div>
CodePudding user response:
Try to add this to your CSS:
.card-active {
width: fit-content;
}
And this to your JavaScript to get when te user mouse is not on hover and change your image rotation to default:
cardParallx.addEventListener('mouseout', (e) => {
let x =(window.innerWidth/2 - e.pageX)/30;
let y =(window.innerHeight/2 - e.pageY)/30;
cardParallx.style.transform =`rotateX(0) rotateY(0)`;
});
To get something like that:
let cardParallx = document.querySelector('.card-active');
cardParallx.addEventListener('mousemove',(e)=>{
let x =(window.innerWidth/2 - e.pageX)/30;
let y =(window.innerHeight/2 - e.pageY)/30;
cardParallx.style.transform =`rotateX(${-y}deg) rotateY(${-x}deg)`;
});
cardParallx.addEventListener('mouseout', (e) => {
let x =(window.innerWidth/2 - e.pageX)/30;
let y =(window.innerHeight/2 - e.pageY)/30;
cardParallx.style.transform =`rotateX(0) rotateY(0)`;
});
.card-active {
width: fit-content
}
<div >
<img src="https://placekitten.com/200/300">
</div>