Last updated on March 1st, 2022 at 11:41 am

In this tutorial we can see how to add div along with the cursor using simple javascript.

Only some simple javascript included and you can just copy and paste it in to a webpage you want the draggable content to be displayed.

Here is the div we are going to include in the script, you may modify it accordingly. The div id is “x”

<div id="x" style="background:#ff0000; padding:10px; width:150px;">Div coming along with mouse!!</div>

Next step is to add the javascript, the function name is move()

<script language="JavaScript" type="text/javascript">

function move()
{
var IE = document.all;

var tempX = 0;
var tempY = 0;

var element=document.getElementById("x");


document.onmousemove=function getMouseXY(abc) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX;
tempY = event.clientY;
} else { // grab the x-y pos.s if browser is NS
tempX = abc.pageX;
tempY = abc.pageY;
}

element.style.marginLeft = tempX + "px";
element.style.marginTop = tempY + "px";
}

}
</script>

As you can see from the script above this section determines where the div is positioned initially when page loads, just before it moves near to the cursor.

var tempX = 0;
var tempY = 0;

Final step is to load the function automatically like below

<body onload="move();">
<div id="x" style="background:#ff0000; padding:10px; width:150px;">Div coming along with mouse!!</div>
</body>

Demo

Leave a Reply

Your email address will not be published. Required fields are marked *