Salman Salman - 5 months ago 26
Javascript Question

How to use the value of a global variable?

I have declared two variables globally in my js code. In one of the function I am storing the value of the screen coordinates in them. Now I want to use these values in another function. How can I do that?

var xCoord;
var yCoord;

var getBrowserCood = $("#Boma").mousedown(function(e) {
if(e.button==2){
xCoord = e.pageX;
yCoord = e.pageY;
}
});

Answer Source

Since you have declared xCoord and yCoord globally, they will be already be available to other functions:

var xCoord;
var yCoord;

var getBrowserCood = $("#Boma").mousedown(function(e) {
    if(e.button==2){
        xCoord = e.pageX;
        yCoord = e.pageY;
    }
});

function anotherFunction() {
    console.log(xCoord);
    console.log(yCoord);
}

anotherFunction();

If you want to keep these variables global, it may be more clear to refer to them using the window object like this:

window.xCoord
window.yCoord

Some related topics which you may want to look into are scope and closures.