0

I need a popup to open from a mouse click's position. From a usability view, when the click's happen near the edges of window, I'm adjusting the position[to the right/ left of click & top/bottom of the click] of popup in JS as below:

function myfunc(e) {
let ele = document.getElementById('my-dialog');
ele.style["left"] =
  (window.innerWidth - e.pageX) < ele.offsetWidth ? e.pageX - ele.offsetWidth : e.pageX;
ele.style["top"] =
  (window.innerHeight - e.pageY) < ele.offsetHeight ? e.pageY - ele.offsetHeight : e.pageY; }

Is there a way this can be achieved using just CSS(or is there a better JS solution to the problem.)

Minimal working code example here.

knomdlo
  • 398
  • 2
  • 14

1 Answers1

0

See a working demo: https://jsfiddle.net/drumperl/ce532rnf/

To get this working, I changed the left and top style settings to add 'px'. According to the spec, a length setting requires a relative or absolute unit of measurement like 'px', '%' or 'em'. https://developer.mozilla.org/en-US/docs/Web/CSS/length

function myfunc(e) {
    let ele = document.getElementById('my-dialog');

    var newLeft = (window.innerWidth - e.pageX) < ele.offsetWidth ? e.pageX - ele.offsetWidth : e.pageX;
    ele.style.left = newLeft + 'px';

    var newTop = (window.innerHeight - e.pageY) < ele.offsetHeight ? e.pageY - ele.offsetHeight : e.pageY;
    ele.style.top = newTop + 'px';
  }
  document.onclick = myfunc;

Hope this helps.

rjoyal
  • 44
  • 2
  • thanks for the mention about adding unit, but I'm checking if there's a CSS trick that can do the same for me to avoid javascript entirely. – knomdlo Aug 12 '18 at 23:30