Please skip the simplest example with two inputs, in which the coordinates of the mouse will be updated horizontally and vertically. No jQuery, thanks)

    4 answers 4

    Using a mouse event . The simplest example below.

    var X = document.getElementById('X'); var Y = document.getElementById('Y'); function pos(e){ X.value = e.pageX; Y.value = e.pageY; } addEventListener('mousemove', pos, false); 
     <!DOCTYPE html> <html> <body> <input type="text" id="X"> <input type="text" id="Y"> </body> </html> 

      MDN: https://developer.mozilla.org/ru/docs/Web/API/MouseEvent

       <!DOCTYPE html> <html> <head> <title>Пример для clientX\clientY</title> <script> function showCoords(evt){ alert( "clientX value: " + evt.clientX + "\n" + "clientY value: " + evt.clientY + "\n" ); } </script> </head> <body onmousedown="showCoords(event)"> <p>Для показа координат мышки нажмите в любом месте страницы.</p> </body> </html> 

      Instead of alert, set the value of your 2 input

        Could be so

         var IE = document.all ? true : false; if (!IE) document.captureEvents(Event.MOUSEMOVE) document.onmousemove = getMouseXY; var tempX = 0; var tempY = 0; function getMouseXY(e) { if (IE) { // grab the xy pos.s if browser is IE tempX = event.clientX + document.body.scrollLeft; tempY = event.clientY + document.body.scrollTop; } else { // grab the xy pos.s if browser is NS tempX = e.pageX; tempY = e.pageY; } if (tempX < 0) { tempX = 0; } if (tempY < 0) { tempY = 0; } document.Show.MouseX.value = tempX; document.Show.MouseY.value = tempY; return true; } 
         <form name="Show"> X <input type="text" name="MouseX" value="0" size="4"><br> Y <input type="text" name="MouseY" value="0" size="4"><br> </form> 

          Made for you an example with two inputs in which coordinates are updated.

           let handleMousemove = (event) => { //console.warn(`${event.x}:${event.y}`); document.getElementById("x").value = `\n${event.x}`; document.getElementById("y").value = `\n${event.y}`; }; let throttle = (func, delay) => { let prev = Date.now() - delay; return (...args) => { let current = Date.now(); if (current - prev >= delay) { prev = current; func.apply(null, args); } } }; document.addEventListener('mousemove', throttle(handleMousemove, 500)); 
           move mouse here <input type="text" id="x"> <input type="text" id="y"> 

            https://jsfiddle.net/178nz54o/ 
          • Here it is better not to use throttle, but to use a debounce. Swipe quickly with the mouse - not the coordinates on which the mouse is located will be shown. - Sasha Omelchenko
          • Thank! Indeed, debounce will be much better here than the throttle :) - xeLL