irishjauntingcar
irishjauntingcar

Reputation: 117

JQuery, why won't my mousemove listener not pass the event object?

I'm using the following the code.

var cursorXPos;
var cursorYPos;

$(document).mousemove( cursorLocation(evt) );

function cursorLocation (evt) {
 cursorXPos = evt.pageX;
 cursorYPos = evt.pageY;
}

But this is giving me an error.

Uncaught TypeError: Cannot read property pageX of undefined.

However, if I use an anonymous function, the event object is passed and everything works fine.

$(document).mousemove( function (evt) {
 cursorXPos = evt.pageX;
 cursorYPos = evt.pageY;
});

Upvotes: 1

Views: 349

Answers (2)

Loyalar
Loyalar

Reputation: 2163

You cannot pass the parameter in the function when you bind the event. You just pass the name of the event, and javascript handles the parameters for you.

var cursorXPos;
var cursorYPos;

$(document).mousemove( cursorLocation ); // <-- here 

function cursorLocation (evt) {
    cursorXPos = evt.pageX;
    cursorYPos = evt.pageY;
}

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388446

You need to pass a function reference to mousemove, don't invoke it(by adding ())

$(document).mousemove( cursorLocation );

Upvotes: 3

Related Questions