View Full Version : Problem with variable scoping

07-12-2011, 03:27 AM
So I just began learning HTML 5, and I'm having some issues with variables not being accessed properly.

var mouseX = 0;
var mouseY = 0;

function mousemove(event) {
var canvas = document.getElementById('apples'),
mouseX = event.pageX - canvas.offsetLeft;
mouseY = event.pageY - canvas.offsetTop;
function mousedown(event) {
if(judge != playerNumber && started && mouseY >= 500-800/7*1.54){
var i = Math.floor(mouseX/800*7);

All of this is in the <head>.

I define the listener here:

var canvas = document.getElementById("apples");
canvas.addEventListener('mousemove', mousemove, false);
canvas.addEventListener('mousedown', mousedown, false);

For some odd reason, mouseX stays at zero outside of mousemove. Inside, it updates properly. It appears to be acting as a local variable. However, mouseY acts properly in both mousemove and mousedown. It retains its value. I've been testing this in Chrome v12.0.742.100, on Windows 7. It does the exact same thing in Firefox. Those are the only parts of the code that reference mouseX, mouseY or the two event listeners.

Any ideas as to how to fix this?