Hello. My task is to move an element to mouse click coordinates.

Those. the user clicks and the element (div, for example) moves there.

As far as I understand, I need to interact with the coordinates of the click and the coordinates of the element.

Please, tell me the algorithm or the solution to this problem.

  • What exactly is the problem? - tutankhamun
  • Add the code you already have - ThisMan
  • The answer is corrected. - Qwertiy

3 answers 3

document.querySelector("div").addEventListener('click', function (e) { var div = e.target var rect = div.getBoundingClientRect() var dx = e.pageX - rect.left, dy = e.pageY - rect.top div.style.background = 'silver' document.addEventListener('click', function handler(e) { div.style.left = e.pageX - dx + 'px' div.style.top = e.pageY - dy + 'px' div.style.background = '' document.removeEventListener('click', handler, true) event.stopPropagation() }, true) }) 
 div { position: absolute; width: 2em; height: 2em; background: blue; } 
 <div></div> 

  • And this is interesting. From: thanks - Bipa

You can use https://jqueryui.com/draggable/ You can also read about drag and drop here https://learn.javascript.ru/drag-and-drop

  $( function() { $( "#drag" ).draggable(); } ); 
 #drag { width: 100px; height: 100px; border: 1px solid #000; } 
 <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div id="drag" class="ui-widget-content">Перетащи меня</div> 

  • Thank you, but this is not my idea) The block should move to the coordinates of the mouse click on the screen - Bipa
  • jQuery did not seem to be asked. - Qwertiy
 <script src="https://code.jquery.com/jquery-2.1.0.js"></script <script> $("html").click (function (event) { $("#elementId").offset ( { left: event.pageX, top: event.pageY }); }); </script> 

By calling the click method on the item id