VanillaJS click drag mouse coordinates

This example uses the addEventListener() method to attach a "mousedown and mousemove" event to a div element

by ndw5015

HTML

<p>This example uses the addEventListener() method to attach a "mousedown and mousemove" event to a div element.</p>

<div id="myDIV"></div>

<p>Click and drag in the rectangle above, and get the X,Y coordinates of your mouse pointer.</p>

<p id="demo"></p>

CSS

div {
  width: 200px;
  height: 100px;
  border: 1px solid black;
}

JavaScript

document.getElementById("myDIV").addEventListener("mousedown", function(e){

    document.getElementById("myDIV").onmousemove = function(e) {
        myFunction(e);
     }
});

document.getElementById("myDIV").addEventListener("mouseup", function(e){
    document.getElementById("myDIV").onmousemove = null
});





function myFunction(e) {
  var x = e.clientX;
  var y = e.clientY;
  var coor = "Coordinates: (" + x + "," + y + ")";
  document.getElementById("demo").innerHTML = coor;
}