Skip to content Skip to sidebar Skip to footer

How To Connect Onmousemove With Onmousedown?

I want to press the mouse button and move the cursor, showing the coordinates of the cursor while the button is pressed. When i stop clicking it should stop showing the coordinates

Solution 1:

Just attach/detach the mousemove handling function upon mousedown/mouseup events:

document.onmousedown = function () {
    document.onmousemove = handleMouseMove;
};
document.onmouseup = function () {
    document.onmousemove = null;
};

functionhandleMouseMove(event) {
  var dot, eventDoc, doc, body, pageX, pageY;

  event = event || window.event;

  if (event.pageX == null && event.clientX != null) {
    eventDoc = (event.target && event.target.ownerDocument) || document;
    doc = eventDoc.documentElement;
    body = eventDoc.body;

    event.pageX = event.clientX +
      (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
      (doc && doc.clientLeft || body && body.clientLeft || 0);
    event.pageY = event.clientY +
      (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
      (doc && doc.clientTop  || body && body.clientTop  || 0 );
  }
  console.log("left: " + event.pageX + "px -- right: " + event.pageY + "px");
}

Post a Comment for "How To Connect Onmousemove With Onmousedown?"