Home > Enterprise >  Change element's position next to the cursor
Change element's position next to the cursor

Time:12-24

Ok so I have this:

x = `${e.clientX window.scrollX}px`
y = `${e.clientY window.scrollY}px`

And it works, but the problem is that the element can extend outside of the page and it creates a scrollbar.
So how can I make it position the div in some way that it wouldn't do that? Is it possible?

CodePudding user response:

I tried to solve this through JS. Here is my code:

var pointerX = -1;
var pointerY = -1;
document.onmousemove = function(event) {
    pointerX = event.pageX;
    pointerY = event.pageY;
}
setInterval(pointerCheck, 1000);
function pointerCheck() {
    console.log('Cursor at: ' pointerX ', ' pointerY);
}

CodePudding user response:

You can take the viewport width / height and the element width / height into account to calculate the x/y coordinates of your element. See the pseudo-code attached to get the idea. Might need a tweak here and there :)

const { clientHeight, clientWidth } = document.documentElement
const { offsetHeight, offsetWidth } = element
const { clientY, clientX } = event
const { scrollY, scrollX } = window

let x = clientX   scrollX

// check if the box would leave the viewport on the right side
if (x   offsetWidth > clientWidth) {
    // move the element to the left
    x -= clientWidth - (x   offsetWidth)
}

let y = clientY   scrollY

// check if the box would leave the viewport on the bottom
if (y   offsetHeight > clientHeight) {
    // move the element to the top
    y -= clientHeight - (y   offsetHeight)
}
  • Related