-1

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;
    }
});
Erazihel
  • 7,295
  • 6
  • 30
  • 53
Salman
  • 393
  • 1
  • 7
  • 23
  • Just use them? But make sure the event handler did actually run before you call the other function. – Bergi Aug 17 '17 at 13:45

1 Answers1

1

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.

Jonathan.Brink
  • 23,757
  • 20
  • 73
  • 115