0

Basic question: I have a function with more than one argument. How can I retrieve the mouse position from inside that function? Here is some code to clarify what I mean.

$(element).on("mousedown",checkDragDropEdit);

function checkDragDropEdit() {
    if($('.editing').length > 0) {
        $('.editing').css('border','3px solid red');
        return
    } else {
        var oldMousePos = checkMousePos();
        $(this).bind("mouseup",function(e) {
            var newMousePos = [e.pageX,e.pageY];
            if(oldMousePos[0] == newMousePos[0] && oldMousePos[1] == newMousePos[1]) {
                //makeEditable($(this));
                edit($(this));
                $(this).off("mousedown",checkDragDropEdit);
            }
            $(this).unbind("mouseup");
        });
    }
}

function checkMousePos(e) {
    return [e.pageX,e.pageY];
}

This is not working, the function returns "Uncaught TypeError: Cannot read property 'pageX' of undefined".

Whereas, if I exchange a part in the "checkDragDropEdit" function to this, I can get the coordinates:

function checkDragDropEdit(e) {
    ...
    var oldMousePos = [e.pageX,e.pageY];
    ...
}

Could somebody explain to me why the functions behave like this and how I can properly retrieve the mouse position inside the upper function? The reason is, I would like to pass more arguments to that function but still be able to retrieve the mouse position once it is executed.

Thanks a lot

tricon
  • 313
  • 4
  • 18

1 Answers1

1

It is because of this line

var oldMousePos = checkMousePos();

function checkMousePos(e) {
    return [e.pageX,e.pageY];
}

It is reading the position based on the Event object . But it is a simple function call.

Pass the event object to the method

function checkDragDropEdit(e) {

   ... // Pass the event object
   var oldMousePos = checkMousePos(e);
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • Thanks a lot...I had to read up a bit more on the event object - I had completely misunderstood how it works and how it is passed along. Thanks Sushanth. – tricon Jun 27 '13 at 06:31
  • Could I ask one more thing though? I cannot get my head around one thing - why is this not working: function checkDragDropEdit(e) { (function(e) { console.log(e) })(); } but this is: function checkDragDropEdit(e) { var oldMousePos = mousePos(e); function mousePos(e) { console.log(e) }} Sorry for those basic questions ;) – tricon Jun 27 '13 at 06:51