amitgupta
amitgupta

Reputation: 1

mouse coordinates in javascript?

I created a small function to get mouse coordinates in div but somehow it is not working. I checked my function thoroughly but I didn't find the bug.

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <script type="text/javascript">
    function SetValues()
    {
    var s = "X:" + window.event.clientX + " Y:" + window.event.clientY ;
    document.getElementById('divCoord').innerHTML = s;
    }
    </script>
    </head>
    <body onmousemove=SetValues()>
    <div id="divCoord"></div>
    </body>
    </html>

Upvotes: 0

Views: 3672

Answers (3)

Ved
Ved

Reputation: 8767

Try this code : JS

 document.onmousemove = getMouseXY;
    var tempX = 0;
    var tempY = 0;
    function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
    } 

HTML

X <input type="text" name="MouseX" value="0" size="4"><br>
Y <input type="text" name="MouseY" value="0" size="4"><br>

Source

Upvotes: 1

David Hellsing
David Hellsing

Reputation: 108520

The window.event property is only present in Internet Explorer, and only in some versions I think. In fact, the entire operation you are trying to do requires some fairly advanced cross-browser coding.

I suggest you consider using a JavaScript framework that normalizes events, such as jQuery.

Using jQuery, and this will work in all browsers:

$(document).mousemove(function(e) {
    $('#divCoord').html('X:' + e.pageX + ' Y:' + e.pageY);
});

Upvotes: 1

devdRew
devdRew

Reputation: 4581

window.event.clientX & window.event.clientY

try:

$(document).ready(function(e) {
    $('body').live('mousemove', function(e) {
        alert('x: ' + window.event.clientX + ', y: ' + window.event.clientY);
    })
});

Upvotes: 0

Related Questions