0

I want to get mouse x and y co-ordinates through JavaScript. I have tried pageX, pageY, clientX, clientY, but nothing is displayed. I have tested this on both IE and Firefox.

Is there something I'm doing wrong in the following event?

var x=0;
var y=0;
function mouseDown(){
    alert("This is displayed");
    evt=event||window.event;
    alert(evt.clientX);
        alert(evt.clientY);
            alert(evt.pageX);
                alert(evt.pagey);
    alert("Flow doesn't reach here...");            
}
1
  • It's interesting that you use proper English in the strings in your code, but when asking for help on the Internet you shorten every word that's longer than 3 letters. Commented Aug 12, 2010 at 9:44

2 Answers 2

1

Yes - you also need to hook the function up as an event handler.

Your event should take an event parameter:

function mouseDown(event) {

And then you need to tell the browser to call your function when the event occurs:

document.onmousedown = mouseDown;
Sign up to request clarification or add additional context in comments.

Comments

1

It's not working because you are not listening for any events. You need to pass this function when any mouse events occur. Try my code below.. gets position on click

function getPos(evt) {
 evt = event || window.event;
 return {x:evt.clientX,y:evt.clientY};
}

Now you can just call this function inside an event listener like this.

addEventListener( 'click' , function(event) {
  var mousex = getPos(event).x;
  Var mousex = getPos(event).y;

  alert(mousex);alert(mousey);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.