Issue
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?
Solution
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)
}
Answered By - csenk
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.