Reputation: 165
I want to get cursorX coordinate from modal generated by jQuery BlockUI plugin. when I try to do so with below code it gives "cursorX is not defined(..)" error.
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;console.log('dsahg');
}
cursorX;
Upvotes: 2
Views: 166
Reputation: 4150
You are trying to access cursorX which is not defined before, You will be getting a reference error because there is no memory assigned for the variable.
cursorX;
Hoisting is JavaScript's default behavior of moving declarations to the top.
Javascript normally looks for all var variable_name;
at first and assign a memory address to it. This is called javaScript Hoisting
If you are not using Strict Mode and trying to assign a value then javaScript is forgiving and it will assign a memory for you and store the value.
You can check that you will have access to clientX
after the reference error if you move your mouse cause javscript will create a memory for you.
Here,
function(e){
cursorX = e.pageX;
cursorY = e.pageY;console.log('dsahg');
}
Your problem here is that cursorX will be defined inside the mousemove
but you are trying to access it before any mousemove.
Obvious Solution is to define it before using it.
var cursorX, cursorY;
outside the function even if it defined at the end of the file will work;
// This will work but will give undefined error cause nothing is assigned to cursorX yet.
console.log(cursorX);
var cursorX = 0, cursorY = 0;
document.onmousemove = function(e) {
cursorX = e.pageX;
cursorY = e.pageY;
console.log(cursorX);
}
console.log(cursorX); //This will print 0 as by now we have assigned a value to it.
//var cursorX,cursorY; This will also work due to variable hoisting
Upvotes: 1
Reputation: 22500
Yes its not defined .you need define with var
like this
console.log(cursorX);//see this its a undefined .its not defined by anything before
var cursorX=""; // default value is empty
var cursorY ="" // default value is empty
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;console.log(cursorX);
}
console.log(cursorX); //its a defined one .but pass the default empty value.Beacuse its show with window load .not after the mouse move
Upvotes: 1