'How to make image follow mouse cursor
I have set up this code where the image follows the mouse cursor. However, for some reason it is not working properly on the second container.
https://codepen.io/stefanomonteiro/pen/jOarjgX
PS: Irrelevant: Stackoerflow first force me to pste the code instead of only codepen link. Now it says it is mostly text. This companies should relly less on bots. It gets annoying sometines :)
const items = document.querySelectorAll('.container')
items.forEach((el) => {
const image = el.querySelector('img')
el.addEventListener('mouseenter', (e) => {
gsap.to(image, { autoAlpha: 1 })
})
el.addEventListener('mouseleave', (e) => {
gsap.to(image, { autoAlpha: 0 })
})
el.addEventListener('mousemove', (e) => {
gsap.set(image, { x: e.pageX, y: e.pageY })
})
})
.container {
display:inline-block;
background:#ff0000;
width:100%;
height:200px;
}
.container:nth-child(2){
background: #00ff00;
}
.container img.swipeimage {
position: absolute;
width: 200px;
height: 200px;
object-fit: cover;
transform: translateX(-50%) translateY(-50%);
z-index: 9;
opacity: 0;
visibily: hidden;
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<div class="container">
<img class="swipeimage" src="https://source.unsplash.com/random">
<div class="text">
<h1>One</h1>
</div>
</div>
<div class="container">
<img class="swipeimage" src="https://source.unsplash.com/random">
<div class="text">
<h1>Two</h1>
</div>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
