Move Div On Cursor Position In jQuery

Other
Demo    Download
File Size: 0.83 KB
Views Total: 1289 views
Last Update:February 21, 2021
Publish Date: November 10, 2020
Official Website: Go to website
License: MIT
Plugin Author: techstorm

Move Div on cursor position follow with mouse is a small javaScript. It makes any element follow your mouse inside a specific page, with a smooth animation.
To move the element along with the mouse movement is not a trick anymore. This method can be done by you using jQuery and CSS method in that particular div.   This method uses few values (or properties) like, position, left, top, and display (optional), which helps locate the part of the mouse cursor.
Here we have to set the position as absolute as this div is relatively following the page.
Here in the given code, if you check the demo, we have taken the circle shape element. The circle moves accordingly with the moment of the mouse cursor. This event is an exciting element that makes a web page look more engaging and attractive.
This code is the best example to experiment with jQuery using CSS, and I hope it’s easy to use and play around with it. Coding is all about trying different variations and permutation-combinations with examples. These codes look exciting and add a bit of fun to the website and increase the skill of using jQuery and a small CSS code. Any doubts? Kindly comment so that we can learn together, explore the world of coding together.

How to used :

Add a class to your figure element with the name of the div:

Therefore, when you move (anywhere) on your web page, it returns all the functions associated with it. There can be an event for the same where we can have on click as well instead of having by mouse movement. Click is based on the activity of mouse click.

<div class="box">
  <div class="circle"></civ>
</div>

Add CSS for design :

<style type="text/css">
body{
  margin:0px;
  padding:0px;
  font-family: 'Roboto', sans-serif;
}
.box{
  width:100%;
  height:500px;
  background:#eaeaea;
  position:relative;
  overflow:hidden;
  cursor:crosshair;
}

.circle{
  background:#f00;
  width:120px;
  height:120px;
  border-radius:50%;
  position:absolute;
  
  transform:translate3d(-50%,-50%,0);
  transition:transform 0.2s cubic-bezier(.02,1.23,.79,1.08);
}
h1 {
	position: absolute;
  left:50%;
  top:50%;
  transform:translate(-50%,-50%);
}
</style>

Add jQuery Script :

In jQuery, we have to direct to the x-axis and y-axis properties with position tracking.

<script type="text/javascript">
$(document).on("click mousemove",".box",function(e){ 
var x = e.clientX;
var y = e.clientY;
var newposX = x - 60;
var newposY = y - 60; $(".circle").css("transform","translate3d("+newposX+"px,"+newposY+"px,0px)");
});

</script>

Done


Nola Arney

Nola Arney is a full stack web developer who has Author at jQuerypost. Her ambition for development is only matched by his desire to find the perfect meme for every occasion.

Related jQuery Plugins