2

I'm writing a script that will repeatedly write my mouse coordinates to an element as I navigate with it. But I'm not sure how to detect information from the mouse. Some one wanna point me in the right direction?

document.getElementById("coords").innerHTML = crdX + ", " + crdY

http://jsfiddle.net/7pj9gpvn/

EDIT: My question is not a duplicate of the proposed question because the proposed question is concerned with the loop aspect of the same problem, whereas mine is concerned with the 'event handling' aspect. I did read and attempt to ascertain the information I needed from that question, but as I am a beginner, I found their code difficult to read.

Musixauce3000
  • 549
  • 1
  • 3
  • 11

2 Answers2

3

Try This works on all browser

http://jsfiddle.net/7hxtLqd4/

<html>

<body>
            <form name="mShow">
        <input type="text" name="MX" value="0" size="4"> X
        <br>
        <input type="text" name="MY" value="0" size="4"> Y
        <br>
    </form>

    <script language="JavaScript1.2">

        var IE = document.all ? true : false

        if (!IE) document.captureEvents(Event.MOUSEMOVE)

        document.onmousemove = getMouse;

        var tempX = 0
        var tempY = 0


        function getMouse(e) {
            if (IE) { 
                tempX = event.clientX + document.body.scrollLeft
                tempY = event.clientY + document.body.scrollTop
            } else { 
                tempX = e.pageX
                tempY = e.pageY
            }

            if (tempX < 0) {
                tempX = 0
            }
            if (tempY < 0) {
                tempY = 0
            }
           // ADD TEMP VALUE FOR FIELDS
            document.mShow.MX.value = tempX
            document.mShow.MY.value = tempY
            return true
        }


    </script>

</body>

</html>
O-mkar
  • 5,430
  • 8
  • 37
  • 61
1

You need to attach a MouseEvent and the event object passed to the handler will give you the coordinates. Attach it to the document if you want to track the movement everywhere. clientX and clientY properties give you local coordinates while screenX and screenY give you global coordinates.

Fiddle: http://jsfiddle.net/AtheistP3ace/7pj9gpvn/4/

HTML:

<p id="coords"></p>
<p id="coords2"></p>

JS:

document.addEventListener('mousemove',
    function (event) {
        var para = document.getElementById('coords');
        para.textContent = event.clientX + ", " + event.clientY;
        var para2 = document.getElementById('coords2');
        para2.textContent = event.screenX + ", " + event.screenY;
    }
);

Feel free to read up on it yourself too: https://developer.mozilla.org/en-US/docs/Web/Events/mousemove

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43