0

I'm wondering how how access returned values from a jQuery function. I know the basic way with a javascript function like so: "var myVar=myFunction();"

But can anyone please show me how I would do it with a jQuery function like this? If i was looking to access the mousePosX and mousePosY? I just don't see a function name to reference. Thanks in advance as always!

    $("#demoCanvas").mousemove(function(event){
        mousePosX = event.pageX;
        mousePosY = event.pageY;
        return mousePosX;
        return mousePosY;
    });//end mousemove()
NickG77
  • 183
  • 2
  • 12
  • where do you want to access those variables? – Austin Brunkhorst May 26 '13 at 21:54
  • I want to use the values for another click function. I guess I could just also grab the positions in the click() like i did in this mousemove(), but now its just a curiosity thing, as it may help shape how I write this app. – NickG77 May 26 '13 at 21:58

2 Answers2

1

Welcome to the world of callbacks.

You pretty much don't access values returned from an event callback. These callbacks run asynchronously from the rest of your code, so any processing that depends on, say mousePosX and mousePosY, needs to happen inside the callback. The callback function you pass to mousemove should fully express the code that should run when that event fires.

Here's a simple example: you might want to pass mousePosX to another function, so that function can do something with it. The callback does not return mousePosX; it calls the other function.

$("#demoCanvas").mousemove(function(event){
    var mousePosX = event.pageX;

    someOtherFunction(mousePosX);
});
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Ok so basically what you're saying is when using a callback like this, I can bring in functions to play with mousePosX, but there's no way to bring mousePosX out to mess with. For a return value like that I have to use normal functions? – NickG77 May 26 '13 at 22:10
  • thanks Matt. Live and learn. I thought i was just missing something since I couldn't find a way to do it. – NickG77 May 26 '13 at 22:17
1

You can always use an object for that purpose:

        function pointer(){
            this.x;
            this.y;
            this.set = function(x,y){this.x=x;this.y=y;}
        }
        var p = new pointer();
        $(document).mousemove(function(e){
            p.set(e.pageX,e.pageY);
        });

You can access the position like this:

$("button").click(function(){
    $("body").append(p.x+" "+p.y+"</br>");
});
Kamen Kotsev
  • 303
  • 1
  • 7