11223342124 11223342124 - 1 year ago 92
Javascript Question

How to make a div follow the cursor, but shifted by Xpx towards the center of window?

Div should follow the cursor, but shifted 20px by X and Y axis toward the center of the screen, based on the quarter in which is the mouse cursor?

Like this: https://i.imgur.com/XaDk1hI.png

I used trigonometry to find vector from cursor to center of the window, so I have cursor coordinates, center coordinates, and third point C, but div moves in strange circles and I don't where I made mistake.

var lt = document.getElementById('lt')
var ltPosition = lt.getBoundingClientRect();
var element = document.getElementById('element');
var mousePosX = 0;
var mousePosY = 0;

document.onmousemove = function(e){
function angle(xCursor, yCursor, xCenter, yCenter){
var distanceA = xCursor - xCenter;
var distanceB = yCursor - yCenter;
var distanceC = Math.sqrt(distanceA*distanceA + distanceB*distanceB);

var theta = Math.atan2(distanceA, distanceB);
theta *= 180 / Math.PI;

var offsetX = distanceC * Math.sin(theta);
var offsetY = distanceC * Math.cos(theta);

function follow(x,y){
element.style.left = x + "px";
element.style.top = y +"px";
follow(e.clientX + offsetX, e.clientY + offsetY);
angle(e.clientX, e.clientY, ltPosition.right, ltPosition.bottom);

Here is fiddle: https://jsfiddle.net/sgvpvqhc/

What else should I do here in order to have this functionality?

Answer Source

What is that theta *= 180 / Math.PI; doing there? sin and cos take the angle in radians, just like atan returns it. If you want to display it, sure, convert it to degrees, but inside the Math API no conversion are needed.

(updated fiddle demo)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download