How to move HTML image to click location with JavaScript

Viewed 71

I am trying to move an HTML image (a black marker) to where I click on a map on the screen. The map has an onclick function which makes a marker visible and move to where the user clicks. However at the moment this only works for the size of screen I am using and whenever the window size is changed the image is several hundred pixels off on each axis.

At the moment I am storing the coordinates of a click in an array and using DOM style.left/top to change the position and using those coordinates plus a set amount of pixels that works for me, but not any other screen. I would like a way to have it it move wherever the user clicks, regardless of the page dimensions.

This is the current way I am doing things, with coords being the array containing the relative coordinates:

document.getElementById('black-marker').style.visibility = 'visible';
document.getElementById('black-marker').style.left = coords[0]-20;
document.getElementById('black-marker').style.top = coords[1]+205;
1 Answers

Click in the red box and the black circle will move to the mouse point.

I got the position of the red box and the mouse position and used them to calculate the relative position for the black box.

const blackMarker = document.getElementById('black-marker');
const parent = blackMarker.parentElement;

parent.addEventListener('click', e => {
  const {
    x,
    y,
    width,
    height
  } = parent.getBoundingClientRect();
  blackMarker.style.left = `${(e.clientX - x) / width * 100}%`;
  blackMarker.style.top = `${(e.clientY - y) / height * 100}%`;
});
body {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}

div {
  position: relative;
  width: 150px;
  height: 150px;
  background-color: red;
}

span {
  position: absolute;
  transform: translate(-50%, -50%);
  width: 25px;
  border-radius: 50%;
  height: 25px;
  background-color: black;
}
<div>
  <span id="black-marker"></span>
</div>

Related