DEV Community

Cover image for Mouse-Tracker, in just 10 lines of JavaScript;
Areeb ur Rub
Areeb ur Rub

Posted on

Mouse-Tracker, in just 10 lines of JavaScript;

Buy Me A Coffee

When I say mouse-tracker I mean it will track the position of cursor on the page, cursor position can be used to add some attractive features in your websites.

Making of Layout

In the above example I am tracking the cursor over whole document you can also track the cursor inside a div, using this feature totally depends on your creativity.
And accordingly you can design the lay out

Example: Tracking inside a <div>

How it's working

In JavaScript there is one event called .onmousemove it is called whenever the cursor make movement.
We can select a element to detect the mouse movement in it element.onmousemove.So whenever this event is called it calculates the position and change the style.top and style.left of desired element.

The calculation part

  • Full Document Calculation

    
    

    var x = event.clientX * 100 / window.innerWidth + "%";
    var y = event.clientY * 100 / window.innerHeight + "%";


for full document tracking we simply take the windows height and width and find it's ratio with the mouse position which is also given in pixel by event.clientX and event.clientY then change it into percentage;

  • <div> Calculation

    
    

    var x = (event.clientX - container.offsetLeft) * 100 / container.offsetWidth + "%";
    var y = (event.clientY - container.offsetTop) * 100 / container.offsetHeight + "%";

for div calculation we just subtract the offset position of div and use the offset height and width instead of window height and width.
The offsetLeft,offsetLTop,offsetHeight, offsetWidth tells us about the position and dimension of <div> including the padding also.

Note:using transform:transalate(x,y); to align or change position make the offset position inaccurate


Follow me for more like this

Read this also:


areeburrub image

Discussion (0)