I’m making a project in html & javascript, and I want to make an image follow the cursor in it. Does anyone know how?
Try setting x y position of the mouse pointer to the x y position of the image:
Used jquery
- Set the
position
of image toabsolute
- Get X and Y coordinates of mouse
- Apply the X coordinate as
left
and Y coordinate astop
to image
$(document).ready(function(){
$(document).mousemove(function(e){
$('img').css('left',e.pageX+"px");
$('img').css('top',e.pageY+"px");
});
});
img {
position: absolute;
transform: translate(-50%, -50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://herbadmother.com/wp-content/themes/thesis_18/custom/rotator/sample-1.jpg" alt="" />