0

I have some items with "click" event. When I click on this items I have to show modal in the place of the click. This modal has position absolute.

I try to get event.pageX and event.pageY

let style = 'top: ' + event.pageX+ 'px; left: ' + event.pageY + 'px;';

but my modal shows very far (look at screen)

http://joxi.ru/brRa073u7J73vA

Viktor
  • 1,532
  • 6
  • 22
  • 61

2 Answers2

0

You can use clientX/clientY event's properties to get the place of the click

Sashabeton
  • 11
  • 1
0

You're probably looking for clientX and clientY, and not pageX and pageY. Also, notice that you must put position: absolute on the modal you're trying to place so it'll work as you're expecting it to (and if you're not too familiar with positioning you should definitely read about it - it's not as simple as it sounds).

pageX and pageY:

Relative to the top left of the fully rendered content area in the browser [...] This point could be anywhere in the browser window and can actually change location if there are embedded scrollable pages embedded within pages and the user moves a scrollbar.

screenX and screenY:

Relative to the top left of the physical screen/monitor.

clientX and clientY:

Relative to the upper left edge of the content area (the viewport) of the browser window. This point does not move even if the user moves a scrollbar from within the browser.

Read more:

Here's a working example:

document.addEventListener("click", e => {
    console.log(e.clientX, e.clientY);
    let modal = document.getElementById("modal");
    modal.style.top = e.clientY+"px";
    modal.style.left = e.clientX+"px";
});
#modal {
    position: absolute;
    width: 100px;
    height: 200px;
    background: blue;
}
<div id="modal"></div>
NonameSL
  • 1,405
  • 14
  • 27
  • I have the same problem when I use clientX and clientY http://joxi.ru/v29L590SZ3ZXDm – Viktor Dec 11 '18 at 14:09
  • @Viktor I don't see your code so I can't really tell you what's wrong - but I've added a working example as inspiration to help you figure out what went wrong. Do notice that you must use `position: absolute` to properly place the modal. – NonameSL Dec 11 '18 at 14:20
  • @Viktor what browser and version are you using? – raphael75 Dec 11 '18 at 14:38
  • @raphael75 @NonameSL I`ve created new theme with detailed description https://stackoverflow.com/questions/53738492/how-to-calculate-left-and-top-for-vue-component-with-position-absolute-when-clic – Viktor Dec 12 '18 at 08:02