0

I am trying to put a input field next to the user's coordinates. During the process, I ran into two problems: firstly, i want the input box to be display: none till the user clicks a key, it didn't work since after clicking the key and setting the display of the box to absolute, it didn't appear. Secondly, i am trying to get the user coordinates without an event (I have that judgement because I don't want that to oblige the user to (mousemove or any other mouse events).

var inputCommand = document.querySelector('.command');
document.addEventListener('keypress', keyPressFunction);

function keyPressFunction(e) {
    inputCommand.style.display = "absolute"; // this does't work
    inputCommand.style.top = "100px"; // this should be replaced with the user's coordinates
    inputCommand.style.left = "500px"; // this should be replaced with the user's coordinates
}
<input type="text" class="command">
Joe Germany
  • 11
  • 1
  • 4

1 Answers1

1

As far as I know, you can't get the mouse coordinates without a mouse event.

Solution: Use a mousemove event to store its position into a variable.

Also, your input is not appearing because absolute is a value for position and not display (as it has been said in comments).

let mouseCoords = { x: 0, y: 0};

document.addEventListener('mousemove', e => {
  mouseCoords = { x: e.clientX, y: e.clientY };
});

const eInput = document.querySelector('input');

document.addEventListener('keypress', () => {
  eInput.style.top = `${mouseCoords.y}px`;
  eInput.style.left = `${mouseCoords.x}px`;
  
  eInput.style.display = 'block';
});
input {
  position: absolute;
  top: 0;
  left: 0;
  
  display: none;
}
<input type="text">
Kévin Bibollet
  • 3,573
  • 1
  • 15
  • 33